package cn.lili.modules.goods.integration.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.lili.cache.Cache;
import cn.lili.cache.CachePrefix;
import cn.lili.common.enums.PromotionTypeEnum;
import cn.lili.common.enums.ResultCode;
import cn.lili.common.enums.SwitchEnum;
import cn.lili.common.event.TransactionCommitSendMQEvent;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.security.AuthUser;
import cn.lili.common.security.context.UserContext;
import cn.lili.common.security.enums.SceneEnums;
import cn.lili.common.thread.ThreadConfig;
import cn.lili.common.utils.*;
import cn.lili.common.vo.ResultMessage;
import cn.lili.exchange.AmqpExchangeProperties;
import cn.lili.modules.constant.CommonConstant;
import cn.lili.modules.distribution.client.DistributionClient;
import cn.lili.modules.distribution.client.DistributionGoodsClient;
import cn.lili.modules.distribution.entity.dos.Distribution;
import cn.lili.modules.goods.entity.dos.*;
import cn.lili.modules.goods.entity.dto.*;
import cn.lili.modules.goods.entity.enums.GoodsAuthEnum;
import cn.lili.modules.goods.entity.enums.GoodsMarketEnum;
import cn.lili.modules.goods.entity.enums.GoodsTypeEnum;
import cn.lili.modules.goods.entity.enums.SalesModeEnum;
import cn.lili.modules.goods.entity.vos.GoodsSkuSpecVO;
import cn.lili.modules.goods.entity.vos.GoodsSkuVO;
import cn.lili.modules.goods.entity.vos.GoodsVO;
import cn.lili.modules.goods.integration.GoodsIntegrationService;
import cn.lili.modules.goods.service.*;
import cn.lili.modules.goods.sku.GoodsSkuBuilder;
import cn.lili.modules.grab.dingdong.reps.goods.DetailRespose;
import cn.lili.modules.grab.dingdong.res.goods.DetailRequest;
import cn.lili.modules.grab.dingdong.service.DingdongGoodsService;
import cn.lili.modules.grab.xdxt.reps.goods.ListGoodsReps;
import cn.lili.modules.grab.xdxt.res.goods.ListGoodsRes;
import cn.lili.modules.grab.xdxt.service.XdxtGoodsService;
import cn.lili.modules.member.client.MemberEvaluationClient;
import cn.lili.modules.member.client.UserClient;
import cn.lili.modules.member.entity.dos.FootPrint;
import cn.lili.modules.member.entity.dos.MemberEvaluation;
import cn.lili.modules.member.entity.dos.User;
import cn.lili.modules.member.entity.dto.EvaluationQueryParams;
import cn.lili.modules.member.entity.enums.EvaluationGradeEnum;
import cn.lili.modules.promotion.client.*;
import cn.lili.modules.promotion.entity.BlindboxRelVO;
import cn.lili.modules.promotion.entity.dos.Coupon;
import cn.lili.modules.promotion.entity.dos.PromotionGoods;
import cn.lili.modules.promotion.entity.dto.search.PointsGoodsSearchParams;
import cn.lili.modules.promotion.entity.dto.search.PromotionGoodsSearchParams;
import cn.lili.modules.promotion.entity.dto.search.RedPackGoodsSearchParams;
import cn.lili.modules.promotion.entity.dto.search.SeckillSearchParams;
import cn.lili.modules.promotion.entity.enums.CouponGetEnum;
import cn.lili.modules.search.entity.dos.EsGoodsIndex;
import cn.lili.modules.search.service.EsGoodsIndexService;
import cn.lili.modules.search.utils.EsIndexUtil;
import cn.lili.modules.store.client.FreightTemplateClient;
import cn.lili.modules.store.client.StoreClient;
import cn.lili.modules.store.entity.dos.Store;
import cn.lili.modules.store.entity.vos.FreightTemplateVO;
import cn.lili.modules.store.entity.vos.StoreVO;
import cn.lili.modules.supplier.entity.dto.SupplierGoodsOperationDTO;
import cn.lili.modules.system.client.PackConfigClient;
import cn.lili.modules.system.client.SettingClient;
import cn.lili.modules.system.entity.dos.Setting;
import cn.lili.modules.system.entity.dto.GoodsSetting;
import cn.lili.modules.system.entity.enums.SettingEnum;
import cn.lili.modules.system.entity.vo.PackConfigVO;
import cn.lili.mybatis.util.SceneHelp;
import cn.lili.routing.GoodsRoutingKey;
import cn.lili.util.AmqpMessage;
import cn.lili.util.AmqpSender;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.apache.shardingsphere.transaction.annotation.ShardingTransactionType;
import org.apache.shardingsphere.transaction.core.TransactionType;
import org.springframework.beans.BeanUtils;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static cn.lili.routing.GoodsRoutingKey.GOODS_DELETE;

/**
 * @author paulG
 * @since 2022/8/15
 **/
@Service
@RequiredArgsConstructor
@Slf4j
public class GoodsIntegrationServiceImpl implements GoodsIntegrationService {

    private final GoodsService goodsService;

    private final DraftGoodsService draftGoodsService;

    private final GoodsSkuService goodsSkuService;

    private final CategoryService categoryService;

    private final BrandService brandService;

    private final WholesaleService wholesaleService;

    private final EsGoodsIndexService goodsIndexService;

    private final GoodsGalleryService goodsGalleryService;

    private final StoreClient storeClient;

    private final SettingClient settingClient;

    private final MemberEvaluationClient memberEvaluationClient;

    private final PromotionGoodsClient promotionGoodsClient;

    private final SeckillClient seckillClient;

    private final RedPackGoodsClient redPackGoodsClient;

    private final PointsGoodsClient pointsGoodsClient;

    private final AmqpSender amqpSender;

    private final AmqpExchangeProperties amqpExchangeProperties;

    private final ApplicationEventPublisher applicationEventPublisher;

    private final PromotionsClient promotionsClient;

    private final MemberCouponClient memberCouponClient;

    private final FreightTemplateClient freightTemplateClient;

    private final Cache cache;

    private final BlindboxRelClient blindboxRelClient;

    private final DingdongGoodsService dingdongGoodsService;

    private final XdxtGoodsService xdxtGoodsService;

    private final UserClient userClient;

    private final DistributionClient distributionClient;

    private final DistributionGoodsClient distributionGoodsClient;

    private final ThreadConfig threadConfig;

    private final GoodsDownRecordService goodsDownRecordService;

    private final PackConfigClient packConfigClient;

    private final GoodsHotPopularService goodsHotPopularService;

    private final GoodsSkuHotPopularService goodsSkuHotPopularService;



    Map<SettingEnum, com.alibaba.fastjson.JSONObject> settings = new HashMap<>();

    @Override
    @Transactional
    @ShardingTransactionType(TransactionType.BASE)
    public void saveGoods(GoodsOperationDTO goodsOperationDTO) {
        // 商品信息校验
        Goods goods = this.wrapperGoods(goodsOperationDTO);
        if (CollUtil.isEmpty(goodsOperationDTO.getSkuList())) {
            throw new ServiceException("规格信息不能为空");
        }
        //是会员，会员价格不能为空
        if (goods.getIsVipGoods() != null && goods.getIsVipGoods()) {
            for (Map<String, Object> map : goodsOperationDTO.getSkuList()) {
                GoodsSku sku = GoodsSkuBuilder.build(goods, map);
                if (sku.getVipPrice() == null || sku.getVipPrice() == 0D) {
                    throw new ServiceException("会员价格为空或为0");
                }
                boolean isFree = sku.getIsFree() != null && sku.getIsFree();
                if (isFree && StringUtils.isEmpty(sku.getThirdPartyPlatformId())) {
                    throw new ServiceException("保税仓商品编号为空");
                }
                if (isFree && sku.getThirdPartyPlatformType() == null) {
                    throw new ServiceException("保税仓商品类型为空");
                }
                if (isFree && StringUtils.isEmpty(sku.getProductCode())) {
                    throw new ServiceException("海关商品备案号为空");
                }
            }
        }
        goods.setUpdateTime(new Date());
        // 保存商品信息
        this.goodsService.saveOrUpdate(goods);
        //当类型为盲盒商品时
        if (GoodsTypeEnum.BLINDBOX_GOODS.name().equals(goodsOperationDTO.getGoodsType())) {
            //新增商品与规则关联关系
            BlindboxRelVO blindboxRelVO = new BlindboxRelVO();
            blindboxRelVO.setGoodsId(goods.getId());
            blindboxRelVO.setRuleId(goodsOperationDTO.getRuleId());
            boolean flag = blindboxRelClient.addBlindboxRel(blindboxRelVO);
            if (!flag) {
                throw new ServiceException(ResultCode.GOODS_NOT_EXIST);
            }
        }
        generateGoodsHandler(goods, goodsOperationDTO);
        // 发送生成商品索引信息
        this.sendGenerateGoods(Collections.singletonList(goods.getId()));
        //判断是否为分销商品,是则同步商品信息到分销商品列表
        log.info("同步分销商品, 是否分销商品字段值, goods.getIsDistributionGoods():{}", goods.getIsDistributionGoods());
        //免税商品不同步到代理商品
        if ((goods.getIsFree() == null || !goods.getIsFree()) &&
                null != goods.getIsDistributionGoods() && goods.getIsDistributionGoods()) {
            log.info("同步分销商品,开始同步");
            Objects.requireNonNull(threadConfig.getAsyncExecutor()).execute(() -> {
                List<GoodsSku> goodsSkuList = goodsSkuService.getGoodsSkuListByGoodsId(goods.getId());
                if (goodsSkuList != null && !goodsSkuList.isEmpty()) {
                    String ids = goodsSkuList.stream().map(GoodsSku::getId).map(String::valueOf).collect(Collectors.joining(","));
                    distributionGoodsClient.distributionCheckGoods(ids);
                }
            });
        }
    }

    @Override
    @Transactional
    @ShardingTransactionType(TransactionType.BASE)
    public void saveDraftGoods(GoodsOperationDTO goodsOperationDTO) {
        goodsOperationDTO.setTemplateGoodsFlag(true);
        // 保存商品信息
        Goods goods = this.wrapperGoods(goodsOperationDTO);
        DraftGoods draftGoods = new DraftGoods();
        if (CharSequenceUtil.isNotEmpty(goodsOperationDTO.getDraftId())) {
            goods.setId(goodsOperationDTO.getDraftId());
        } else {
            goods.setId(SnowFlake.getIdStr());
        }
        BeanUtils.copyProperties(goods, draftGoods);
        // 保存商品信息
        this.draftGoodsService.saveOrUpdate(draftGoods);
        generateGoodsHandler(goods, goodsOperationDTO);

    }

    @Override
    @Transactional
    @ShardingTransactionType(TransactionType.BASE)
    public void updateGoods(GoodsOperationDTO goodsOperationDTO) {

        Goods goods = goodsService.getById(goodsOperationDTO.getGoodsId());
        if (goods == null) {
            throw new ServiceException(ResultCode.GOODS_NOT_EXIST);
        }
        //代理商品无法在此处修改
        if (Boolean.TRUE.equals(goods.getIsProxyGoods()) && !Objects.requireNonNull(UserContext.getCurrentUser()).getScene().equals(SceneEnums.MANAGER)) {
            throw new ServiceException(ResultCode.PROXY_GOODS_CANT_UPDATE_HEAR);
        }

        // 城市分站不能修改商品
        if (SceneEnums.URBAN_SUBSTATION.equals(Objects.requireNonNull(UserContext.getCurrentUser()).getScene())) {
            throw new ServiceException(ResultCode.URBAN_GOODS_CANT_UPDATE_HEAR);
        }

        goods = this.wrapperGoods(goodsOperationDTO);
        if (!goodsOperationDTO.getReadyForSale()) {
            goods.setMarketEnable(GoodsMarketEnum.DOWN.name());
        }

        //重新确定商品的展示价格和积分
        List<Map<String, Object>> skus = goodsOperationDTO.getSkuList();
        Double minPrice = null;
        Double minVipPrice = null;
        Double minGoodsVipPrice = null;
        String greenScore = null;
        String thirdPartyPlatformId = null;
        boolean isFree = false;
        for (Map<String, Object> map : skus) {
            Double price = map.containsKey(GoodsSku.PRICE_KEY) ? Double.valueOf(map.get(GoodsSku.PRICE_KEY).toString()) : 0;
            Double vipPrice = map.containsKey(GoodsSku.VIP_PRICE_KEY) ? Double.valueOf(map.get(GoodsSku.VIP_PRICE_KEY).toString()) : 0;
            Double cost = map.containsKey(GoodsSku.COST_KEY) ? Double.valueOf(map.get(GoodsSku.COST_KEY).toString()) : 0;
            if (map.containsKey("id")) {
                //校验商品是否存在
                GoodsSku goodsSku = goodsSkuService.getById(map.get("id").toString());
                if (goodsSku == null) {
                    throw new ServiceException(ResultCode.GOODS_NOT_EXIST);
                }
                //校验价格是否小于原价
//                Double price = map.containsKey(GoodsSku.PRICE_KEY) ? Double.valueOf(map.get(GoodsSku.PRICE_KEY).toString()) : 0;
//                if (price < cost) {
//                    throw new ServiceException(ResultCode.PROXY_PRICE_CANT_SMALL_THAN_ORIGIN, goodsSku.getSimpleSpecs());
//                }
            }

            if (price < cost) {
                throw new ServiceException(ResultCode.PROXY_PRICE_CANT_SMALL_THAN_ORIGIN);
            }

            if(null == minPrice){
                minPrice = price;
                if(map.containsKey(GoodsSku.GREEN_SCORE) && null!=map.get(GoodsSku.GREEN_SCORE)){
                    greenScore = String.valueOf(map.get(GoodsSku.GREEN_SCORE));
                }
            }else{
                if(price < minPrice){
                    minPrice = price;
                    if(map.containsKey(GoodsSku.GREEN_SCORE) && null!=map.get(GoodsSku.GREEN_SCORE)){
                        greenScore = String.valueOf(map.get(GoodsSku.GREEN_SCORE));
                    }
                }
            }
            if(null == minVipPrice || vipPrice < minVipPrice) {
                minVipPrice = vipPrice;
                minGoodsVipPrice = price;
            }
        }
        if(null!=greenScore){
            goods.setDefaultSkuGreenScore(new BigDecimal(greenScore));
        }
        if(null!=minPrice){
            goods.setPrice(minPrice); //最小价格
        }
        if(null != minVipPrice){
            goods.setVipPrice(minVipPrice); //最小价格
        }
        //不是会员清空会员价格
        if (goods.getIsVipGoods() != null && !goods.getIsVipGoods()) {
            goods.setVipPrice(null);
        }
        //是会员，商品最低价展示，会员价
        if (goods.getIsVipGoods() != null && goods.getIsVipGoods()) {
            goods.setPrice(minGoodsVipPrice);
        }
        //免税商品
        if (goods.getMarketEnable().equals(GoodsMarketEnum.UPPER.name()) && goods.getAuthFlag().equals(GoodsAuthEnum.PASS.name()) && goods.getIsFree() != null && goods.getIsFree() && goods.getThirdPartyPlatformType() != null && goods.getThirdPartyPlatformType() == 4 && StrUtil.isNotEmpty(goods.getStoreCategoryPath())) {
            //设置免税商品上面的店铺分类-1
            String[] storeCategoryIdArray = goods.getStoreCategoryPath().split(",");
            Double redisNum = cache.increment(CommonConstant.STORE_CATEGORY_NUM + storeCategoryIdArray[0], -1.0, null, null, false);
            if (redisNum < 0) {
                cache.remove(CommonConstant.STORE_CATEGORY_NUM + storeCategoryIdArray[0]);
            }
        }
        // 更新商品信息
        goodsService.updateGoods(goods);
        if (goods.getMarketEnable().equals(GoodsMarketEnum.DOWN.name()) || goods.getAuthFlag().equals(GoodsAuthEnum.TOBEAUDITED.name())) {
            removeGoods(Collections.singletonList(goods.getId()));
        }
        goodsService.clearCache(goods.getId());
        generateGoodsHandler(goods, goodsOperationDTO);

        // 发送生成商品索引信息
        this.sendGenerateGoods(Collections.singletonList(goods.getId()));
        //判断是否为分销商品,是则同步商品信息到分销商品列表
        log.info("同步分销商品, 是否分销商品字段值, goods.getIsDistributionGoods():{}", goods.getIsDistributionGoods());
        if (null != goods.getIsDistributionGoods() && goods.getIsDistributionGoods()) {
            log.info("同步分销商品,开始同步");
            List<GoodsSku>  goodsSkuList = goodsSkuService.getGoodsSkuListByGoodsId(goods.getId());
            if(goodsSkuList!=null && !goodsSkuList.isEmpty()){
                String ids = goodsSkuList.stream().map(GoodsSku::getId).map(String::valueOf).collect(Collectors.joining(","));
                distributionGoodsClient.distributionCheckGoods(ids);
            }
        }
    }

    @Override
    @Transactional
    @ShardingTransactionType(TransactionType.BASE)
    public void updateGoods(String goodsIds, String categoryPathIds) {
        // 城市分站不能修改商品
        if (SceneEnums.URBAN_SUBSTATION.equals(Objects.requireNonNull(UserContext.getCurrentUser()).getScene())) {
            throw new ServiceException(ResultCode.URBAN_GOODS_CANT_UPDATE_HEAR);
        }
        List<Goods> goodsList = goodsService.list(new LambdaQueryWrapper<Goods>().in(Goods::getId, (Object[]) goodsIds.split(",")));
        if (goodsList == null) {
            throw new ServiceException(ResultCode.GOODS_NOT_EXIST);
        }
        //代理商品无法在此处修改 ==》管理员除外
        if (!Objects.requireNonNull(UserContext.getCurrentUser()).getScene().equals(SceneEnums.MANAGER)) {
            for (Goods goods : goodsList) {
                if (Boolean.TRUE.equals(goods.getIsProxyGoods())) {
                    throw new ServiceException(goods.getGoodsName() + ":" + ResultCode.PROXY_GOODS_CANT_UPDATE_HEAR.message());
                }
            }
        }
        //修改sku的分类
        LambdaUpdateWrapper<GoodsSku> skuLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        skuLambdaUpdateWrapper.set(GoodsSku::getCategoryPath, categoryPathIds);
        skuLambdaUpdateWrapper.set(GoodsSku::getCategoryPathSon,null);
        skuLambdaUpdateWrapper.set(GoodsSku::getCategoryPathSonName,null);
        skuLambdaUpdateWrapper.in(GoodsSku::getGoodsId, (Object[]) goodsIds.split(","));
        goodsSkuService.update(skuLambdaUpdateWrapper);

        //修改goods的分类
        LambdaUpdateWrapper<Goods> goodsLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        goodsLambdaUpdateWrapper.set(Goods::getCategoryPath, categoryPathIds);
        goodsLambdaUpdateWrapper.set(Goods::getCategoryPathSon,null);
        goodsLambdaUpdateWrapper.set(Goods::getCategoryPathSonName,null);
        goodsLambdaUpdateWrapper.in(Goods::getId, (Object[]) goodsIds.split(","));
        goodsService.update(goodsLambdaUpdateWrapper);

        //发送生成商品索引信息 并清除缓存信息
        for (Goods goods : goodsList) {
            this.goodsService.clearCache(goods.getId());
            this.sendGenerateGoods(Collections.singletonList(goods.getId()));
        }
        List<GoodsSku> goodsSkus = goodsSkuService.list(new LambdaQueryWrapper<GoodsSku>().in(GoodsSku::getGoodsId, (Object[]) goodsIds.split(",")));
        goodsSkus.forEach(i -> this.goodsSkuService.clearCache(i.getId()));
    }


    @Override
    @Transactional
    @ShardingTransactionType(TransactionType.BASE)
    public ResultMessage<Object> addCategoryPathSon(String ids, String categoryPathSon, String categoryPathSonName) {
        // 城市分站不能修改商品
        if (SceneEnums.URBAN_SUBSTATION.equals(Objects.requireNonNull(UserContext.getCurrentUser()).getScene())) {
            throw new ServiceException(ResultCode.URBAN_GOODS_CANT_UPDATE_HEAR);
        }
        List<Goods> goodsList = goodsService.list(new LambdaQueryWrapper<Goods>().in(Goods::getId, (Object[]) ids.split(",")));
        if (goodsList == null) {
            throw new ServiceException(ResultCode.GOODS_NOT_EXIST);
        }
        //代理商品无法在此处修改 ==>管理员除外
        if (!Objects.requireNonNull(UserContext.getCurrentUser()).getScene().equals(SceneEnums.MANAGER)) {
            for (Goods goods : goodsList) {
                if (Boolean.TRUE.equals(goods.getIsProxyGoods())) {
                    throw new ServiceException(goods.getGoodsName() + ":" + ResultCode.PROXY_GOODS_CANT_UPDATE_HEAR.message());
                }
            }
        }
        //为主分类没有的商品添加，分类
        List<Goods> goodsCategoryPathSonList = goodsService.list(new LambdaQueryWrapper<Goods>().in(Goods::getId, (Object[]) ids.split(","))
                .notLike(Goods::getCategoryPath, categoryPathSon));
        if (CollectionUtil.isEmpty(goodsCategoryPathSonList)) {
            return ResultUtil.data(true);
        }
        //批量添加分类
        List<String> goodsIdList = goodsCategoryPathSonList.stream().map(Goods::getId).toList();
        List<GoodsSku> goodsSkus = goodsSkuService.list(new LambdaQueryWrapper<GoodsSku>().in(GoodsSku::getGoodsId, goodsIdList));
        goodsSkuService.updateCategoryById(goodsSkus.stream().map(GoodsSku::getId).collect(Collectors.joining(",")), categoryPathSon, categoryPathSonName);
        goodsService.updateCategoryById(String.join(",",goodsIdList), categoryPathSon, categoryPathSonName);

        //发送生成商品索引信息 并清除缓存信息
        for (Goods goods : goodsList) {
            this.goodsService.clearCache(goods.getId());
            this.sendGenerateGoods(Collections.singletonList(goods.getId()));
        }
        goodsSkus.forEach(i -> this.goodsSkuService.clearCache(i.getId()));
        return ResultUtil.data(true);
    }

    @Override
    @Transactional
    @ShardingTransactionType(TransactionType.BASE)
    public void saveSupplierGoods(SupplierGoodsOperationDTO supplierGoodsOperationDTO) {
        // 构建商品基本信息
        Goods goods = this.wrapperGoods(supplierGoodsOperationDTO);
        // 保存商品信息
        this.goodsService.save(goods);
        // 构建商品 sku基本信息
        generateGoodsHandler(goods, supplierGoodsOperationDTO);
        // 发送生成商品索引信息
        this.sendGenerateGoods(Collections.singletonList(goods.getId()));

        if (null != goods.getGoodsFrom() && goods.getGoodsFrom() == 2) {
            //发送商品采集完成后good信息
            this.sendGrabGoods(goods);
        }

    }


    @Override
    @Transactional
    @ShardingTransactionType(TransactionType.BASE)
    public void updateSupplierGoods(SupplierGoodsOperationDTO supplierGoodsOperationDTO) {
        // 构建商品基本信息
        Goods goods = this.wrapperGoods(supplierGoodsOperationDTO);
        if (!supplierGoodsOperationDTO.getReadyForSale()) {
            goods.setMarketEnable(GoodsMarketEnum.DOWN.name());
        }
        // 更新商品信息
        goodsService.updateGoods(goods);


        // 更新代理商品
        /*LambdaUpdateWrapper<Goods> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(Goods::getMarketEnable, GoodsMarketEnum.DOWN.name());
        updateWrapper.set(Goods::getAuthFlag, GoodsAuthEnum.TOBEAUDITED.name());
        updateWrapper.eq(Goods::getSupplierGoodsId, goods.getId());
        goodsService.update(updateWrapper);*/

        List<String> goodsIds = Lists.newArrayList();
        goodsIds.add(goods.getId());
        LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Goods::getSupplierGoodsId, goods.getId());
        List<Goods> goodsList = goodsService.list(queryWrapper);
        if (!goodsList.isEmpty()) {
            List<GoodsSku> goodsSkus = goodsSkuService.list(new LambdaQueryWrapper<GoodsSku>()
                    .in(GoodsSku::getGoodsId, goodsList.stream().map(Goods::getId).collect(Collectors.toList()))
                    .select(GoodsSku::getId, GoodsSku::getGoodsId));

            goodsList.stream().forEach(goods1 -> {
                goodsIds.add(goods1.getId());
                goods1.setMarketEnable(GoodsMarketEnum.DOWN.name());
                goods1.setAuthFlag(GoodsAuthEnum.TOBEAUDITED.name());
                goods1.setPrice(goods.getPrice());
                goods1.setVipPrice(goods.getVipPrice());
                goods1.setCategoryPathSon(goods.getCategoryPathSon());
                goods1.setCategoryPathSonName(goods.getCategoryPathSonName());
                goodsService.updateById(goods1);
                this.goodsService.clearCache(goods1.getId());
            });

            if (CollectionUtil.isNotEmpty(goodsSkus)) {
                LambdaUpdateWrapper<GoodsSku> goodsSkuLambdaUpdateWrapper =  new LambdaUpdateWrapper<>();
                goodsSkuLambdaUpdateWrapper.in(GoodsSku::getId, goodsSkus.stream().map(GoodsSku::getId).collect(Collectors.toList()));
                goodsSkuLambdaUpdateWrapper.set(GoodsSku::getCategoryPathSon, goods.getCategoryPathSon());
                goodsSkuLambdaUpdateWrapper.set(GoodsSku::getCategoryPathSonName, goods.getCategoryPathSonName());
                this.goodsSkuService.update(goodsSkuLambdaUpdateWrapper);
                goodsSkus.forEach(i -> this.goodsSkuService.clearCache(i.getId()));
            }
        }

        // 构建商品 sku基本信息
        generateGoodsHandler(goods, supplierGoodsOperationDTO);
        // 发送生成商品索引信息
        this.sendGenerateGoods(goodsIds);

        // 更新装修商品数据
        this.sendUpdatePageDataGoods(goodsIds);
    }

    @Override
    @Transactional
    @ShardingTransactionType(TransactionType.BASE)
    public void addSupplierCategoryPathSon(String ids, String categoryPathSon, String categoryPathSonName) {
        List<String> goodsIdList = new ArrayList<>();
        List<String> supplierGoodsIds = Arrays.stream(ids.split(",")).toList();

        LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.and( q-> q.in(Goods::getSupplierGoodsId, supplierGoodsIds).or().in(Goods::getId, supplierGoodsIds));
        queryWrapper.notLike(Goods::getCategoryPath, categoryPathSon);
        List<Goods> goodsList = goodsService.list(queryWrapper);
        if (!goodsList.isEmpty()) {
//            for (Goods goods : goodsList) {
//                if (StringUtils.isNotEmpty(goods.getCategoryPath()) && goods.getCategoryPath().contains(categoryPathSon)) {
//                    throw new ServiceException("商品:" + goods.getGoodsName() + "分类:" + categoryPathSonName + ",分类已存在");
//                }
//            }
            List<String> idList = goodsList.stream().map(Goods::getId).toList();
            goodsIdList.addAll(idList);
            List<GoodsSku> goodsSkus = goodsSkuService.list(new LambdaQueryWrapper<GoodsSku>().in(GoodsSku::getGoodsId, goodsIdList));
            //sku添加分类
            goodsSkuService.updateCategoryByIdOrSupplierId(goodsSkus.stream().map(GoodsSku::getId).collect(Collectors.joining(",")), categoryPathSon, categoryPathSonName);
            //goods添加分类
            goodsService.updateCategoryByIdOrSupplierId(String.join(",",goodsIdList), categoryPathSon, categoryPathSonName);

            //发送生成商品索引信息 并清除缓存信息
            for (Goods goods : goodsList) {
                this.goodsService.clearCache(goods.getId());
                this.sendGenerateGoods(Collections.singletonList(goods.getId()));
            }
            goodsSkus.forEach(i -> this.goodsSkuService.clearCache(i.getId()));
        }
    }

    @Override
    @Transactional
    @ShardingTransactionType(TransactionType.BASE)
    public void updateSupplierGoodsCategory(String goodsIds, String categoryPath) {

        List<String> goodsIdList = new ArrayList<>();

        List<String> supplierGoodsIds = Arrays.stream(goodsIds.split(",")).toList();

        //修改供应商商品sku的分类
        LambdaUpdateWrapper<GoodsSku> skuLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        skuLambdaUpdateWrapper.set(GoodsSku::getCategoryPath, categoryPath);
        skuLambdaUpdateWrapper.and(q-> q.in(GoodsSku::getGoodsId, supplierGoodsIds).or().in(GoodsSku::getSupplierGoodsId, supplierGoodsIds));
        goodsSkuService.update(skuLambdaUpdateWrapper);

        //修改应商商品的分类
        LambdaUpdateWrapper<Goods> goodsLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        goodsLambdaUpdateWrapper.set(Goods::getCategoryPath, categoryPath);
        goodsLambdaUpdateWrapper.and(q -> q.in(Goods::getId, supplierGoodsIds).or().in(Goods::getSupplierGoodsId, supplierGoodsIds));
        goodsService.update(goodsLambdaUpdateWrapper);

        //发送mq，更新供应商商品的es数据
        this.sendGenerateGoods(supplierGoodsIds);

        LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.and( q-> q.in(Goods::getSupplierGoodsId, supplierGoodsIds).or().in(Goods::getId, supplierGoodsIds));
        List<Goods> goodsList = goodsService.list(queryWrapper);
        if (!goodsList.isEmpty()) {
            List<String> idList = goodsList.stream().map(item -> item.getId()).collect(Collectors.toList());
            goodsIdList.addAll(idList);

            //修改sku的分类
            LambdaUpdateWrapper<GoodsSku> skuLambdaUpdateWrapper1 = new LambdaUpdateWrapper<>();
            skuLambdaUpdateWrapper1.set(GoodsSku::getCategoryPath, categoryPath);
            skuLambdaUpdateWrapper1.in(GoodsSku::getGoodsId, goodsIdList);
            goodsSkuService.update(skuLambdaUpdateWrapper1);

            //修改goods的分类
            LambdaUpdateWrapper<Goods> goodsLambdaUpdateWrapper1 = new LambdaUpdateWrapper<>();
            goodsLambdaUpdateWrapper1.set(Goods::getCategoryPath, categoryPath);
            goodsLambdaUpdateWrapper1.in(Goods::getId, goodsIdList);
            goodsService.update(goodsLambdaUpdateWrapper1);

            for (String goodsId : goodsIdList) {
                this.goodsService.clearCache(goodsId);
            }
            List<GoodsSku> goodsSkus = goodsSkuService.list(new LambdaQueryWrapper<GoodsSku>().in(GoodsSku::getGoodsId,
                    goodsIdList));
            goodsSkus.forEach(i -> this.goodsSkuService.clearCache(i.getId()));

            //发送mq，更新店铺商品的es数据
            this.sendGenerateGoods(goodsIdList);

        }


//        // 构建商品 sku基本信息
//        generateGoodsHandler(goods, supplierGoodsOperationDTO);
//        // 发送生成商品索引信息
//        this.sendGenerateGoods(goodsIds);
    }

    @Override
    @Transactional
    @ShardingTransactionType(TransactionType.BASE)
    public Boolean updateGoodsStatus(GoodsUpdateStatusDTO params) {
        try {
            //检测企叮咚商品与壹邦玖商品是否为上架
            this.qddCheck(params);

            // 检查商品是否可更新状态
            this.checkUpdateGoodsStatusAvailable(params);

            // 执行更新商品状态
            boolean result = this.executeGoodsStatusUpdate(params);

            // 发送商品状态更新消息
            this.sendGoodsStatusUpdateMessage(params);

            if (GoodsMarketEnum.DOWN.name().equals(params.getGoodsStatus())) {
                // 更新装修商品数据
                this.sendUpdatePageDataGoods(params.getGoodsIds());
                //删除拼团和秒杀商品,红包商品,积分商品
                this.removeGoods(params.getGoodsIds());

                if (SceneEnums.MANAGER.name().equals(Objects.requireNonNull(UserContext.getCurrentUser()).getScene().name())) {
                    // 记录下架原因
                    saveGoodsDownRecord(params);
                }

            }
            return result;
        } catch (IllegalArgumentException iae) {
            log.error("商品状态更新失败，参数错误", iae);
            throw new ServiceException(ResultCode.PARAMS_ERROR, "商品状态更新失败");
        } catch (ServiceException se) {
            throw se;
        } catch (Exception e) {
            log.error("商品状态更新失败，参数错误", e);
            throw new ServiceException(ResultCode.PARAMS_ERROR, "商品状态更新失败");
        }
    }

    private void saveGoodsDownRecord(GoodsUpdateStatusDTO params) {
        List<GoodsDownRecord> goodsDownRecordList = Lists.newArrayList();
        if (!params.getGoodsIds().isEmpty()) {
            params.getGoodsIds().forEach(id -> {
                Goods goods = goodsService.getById(id);
                GoodsDownRecord goodsDownRecord = new GoodsDownRecord();
                goodsDownRecord.setGoodsName(goods.getGoodsName());
                goodsDownRecord.setGoodsId(goods.getId());
                goodsDownRecord.setScene(goods.getScene());
                if (StringUtils.isNotEmpty(goods.getStoreId())) {
                    goodsDownRecord.setStoreId(goods.getStoreId());
                }
                if (StringUtils.isNotEmpty(goods.getSupplierId())) {
                    goodsDownRecord.setSupplierId(goods.getSupplierId());
                }
                goodsDownRecord.setReason(params.getUnderReason());
                goodsDownRecord.setCreateTime(new Date());
                goodsDownRecordList.add(goodsDownRecord);
            });
        }
        goodsDownRecordService.saveBatch(goodsDownRecordList);
    }

    /**
     * 删除商品
     * @param goodsIds 商品id
     */
    public void removeGoods(List<String> goodsIds) {
        if (CollectionUtil.isEmpty(goodsIds)) {
            return;
        }
        //下架，拼团商品
        PromotionGoodsSearchParams searchParams = new PromotionGoodsSearchParams();
        searchParams.setGoodsId(String.join(",", goodsIds));
        promotionGoodsClient.deletePromotionGoods(searchParams);

        // 删除新品爆款
        LambdaUpdateWrapper<GoodsSkuHotPopular> deleteGoodsSkuHot = new LambdaUpdateWrapper<>();
        deleteGoodsSkuHot.in(GoodsSkuHotPopular::getGoodsId, goodsIds);
        goodsSkuHotPopularService.remove(deleteGoodsSkuHot);

        LambdaUpdateWrapper<GoodsHotPopular> deleteGoodsHot = new LambdaUpdateWrapper<>();
        deleteGoodsHot.in(GoodsHotPopular::getGoodsId, goodsIds);
        goodsHotPopularService.remove(deleteGoodsHot);

        LambdaQueryWrapper<GoodsSku> goodsSkuLambdaQueryWrapper = new LambdaQueryWrapper<>();
        goodsSkuLambdaQueryWrapper.in(GoodsSku::getGoodsId, goodsIds);
        goodsSkuLambdaQueryWrapper.select(GoodsSku::getId);
        List<GoodsSku> goodsSkuList = goodsSkuService.list(goodsSkuLambdaQueryWrapper);
        if (CollectionUtil.isNotEmpty(goodsSkuList)) {
            //下架秒杀商品
            SeckillSearchParams seckillSearchParams = new SeckillSearchParams();
            seckillSearchParams.setSkuId(goodsSkuList.stream().map(GoodsSku::getId).collect(Collectors.joining(",")));
            seckillClient.deleteSeckillGoods(seckillSearchParams);
            //下架红包广场商品
            RedPackGoodsSearchParams redPackGoodsSearchParams = new RedPackGoodsSearchParams();
            redPackGoodsSearchParams.setSkuId(goodsSkuList.stream().map(GoodsSku::getId).collect(Collectors.joining(",")));
            redPackGoodsClient.deleteRedPackGoods(redPackGoodsSearchParams);
            //下架积分商品
            PointsGoodsSearchParams pointsGoodsSearchParams = new PointsGoodsSearchParams();
            pointsGoodsSearchParams.setSkuId(goodsSkuList.stream().map(GoodsSku::getId).collect(Collectors.joining(",")));
            pointsGoodsClient.deletePointsGoods(pointsGoodsSearchParams);
        }
    }

    @Override
    @Transactional
    @ShardingTransactionType(TransactionType.BASE)
    public Boolean updateSalesVolume(GoodsUpdateStatusDTO params) {
        //更新商品虚拟销量
        for (String goodsId:params.getGoodsIds()) {
            Goods goods = goodsService.getById(goodsId);
            Integer goodsVirtualBuyCount = goods.getVirtualBuyCount() == null ? 0 : goods.getVirtualBuyCount();
            goods.setVirtualBuyCount(goodsVirtualBuyCount + params.getVirtualBuyCount());
            goodsService.updateById(goods);
        }
        //更新sku虚拟销量
        List<GoodsSku> goodsSkuList = goodsSkuService.getGoodsSkuListByGoodsId(params.getGoodsIds());
        for (GoodsSku goodsSku:goodsSkuList) {
            Integer goodsSkuVirtualBuyCount = goodsSku.getVirtualBuyCount() == null ? 0 : goodsSku.getVirtualBuyCount();
            goodsSku.setVirtualBuyCount(goodsSkuVirtualBuyCount + params.getVirtualBuyCount());
            goodsSkuService.updateById(goodsSku);
        }

        //更新商品上下架状态
        params.setGoodsStatus(GoodsMarketEnum.UPPER.name());
        return updateGoodsStatus(params);
    }

    @Override
    @Transactional
    @ShardingTransactionType(TransactionType.BASE)
    public Boolean updateEvaluateVolume(GoodsUpdateStatusDTO params) {
        //更新商品虚拟评价
        ThreadPoolUtil.execute(() -> {
            for (String goodsId:params.getGoodsIds()) {
                Goods goods = goodsService.getById(goodsId);
                Integer goodsVirtualEvaluateCount = goods.getVirtualEvaluateCount() == null ? 0 : goods.getVirtualEvaluateCount();
                goods.setVirtualEvaluateCount(goodsVirtualEvaluateCount + params.getVirtualEvaluateCount());
                goodsService.updateById(goods);

                //添加默认好评
                for(int i=0;i<params.getVirtualEvaluateCount();i++){
                    MemberEvaluation memberEvaluation = new MemberEvaluation();
                    memberEvaluation.setContent(StringUtils.isNotEmpty(params.getVirtualEvaluateContent())?params.getVirtualEvaluateContent():"系统默认好评");
                    memberEvaluation.setGoodsId(goodsId);
                    memberEvaluation.setGoodsImage(params.getGoodsImage());
                    memberEvaluation.setGoodsName(StringUtils.isNotEmpty(params.getGoodsName()) ? params.getGoodsName() : goods.getGoodsName());
                    memberEvaluation.setGrade(StringUtils.isNotEmpty(params.getGrade()) ? params.getGrade() : EvaluationGradeEnum.GOOD.name());
                    memberEvaluation.setMemberName(params.getMemberName());
                    memberEvaluation.setMemberProfile(params.getMemberProfile());
                    memberEvaluation.setStoreId(goods.getStoreId());
                    int score = 5;
                    if (memberEvaluation.getGrade().equals(EvaluationGradeEnum.MODERATE.name())) {
                        score = 4;
                    }
                    if (memberEvaluation.getGrade().equals(EvaluationGradeEnum.WORSE.name())) {
                        score = 3;
                    }
                    memberEvaluation.setDeliveryScore(score);
                    memberEvaluation.setDescriptionScore(score);
                    memberEvaluation.setServiceScore(score);
                    memberEvaluation.setStatus(SwitchEnum.OPEN.name());
                    memberEvaluation.setCreateTime(params.getCreateTime());
                    memberEvaluationClient.addMemberEvaluation(memberEvaluation);
                }
            }
        });
        //更新sku虚拟评价
        List<GoodsSku> goodsSkuList = goodsSkuService.getGoodsSkuListByGoodsId(params.getGoodsIds());
        for (GoodsSku goodsSku:goodsSkuList) {
            Integer goodsSkuVirtualEvaluateCount = goodsSku.getVirtualEvaluateCount() == null ? 0 : goodsSku.getVirtualEvaluateCount();
            goodsSku.setVirtualEvaluateCount(goodsSkuVirtualEvaluateCount + params.getVirtualEvaluateCount());
            goodsSkuService.updateById(goodsSku);
        }

        //更新商品上下架状态
        params.setGoodsStatus(GoodsMarketEnum.UPPER.name());
        return updateGoodsStatus(params);
    }

    /**
     * 检测企叮咚商品是否为上架
     * @param params
     * */
    public void qddCheck(GoodsUpdateStatusDTO params){
        if(GoodsMarketEnum.UPPER.name().equals(params.getGoodsStatus())){
            params.getGoodsIds().forEach(e->{
                Goods byId = goodsService.getById(e);
                //企叮咚
                if (byId.getThirdPartyPlatformId() != null && Integer.valueOf(2).equals(byId.getThirdPartyPlatformType())) {
                    DetailRequest detailRequest = new DetailRequest();
                    detailRequest.setId(byId.getThirdPartyPlatformId());
                    DetailRespose detail = dingdongGoodsService.detail(detailRequest);
                    if(detail == null || "0".equals(detail.getGoods().getIf_b2b())){
                        throw new ServiceException(ResultCode.PARAMS_ERROR, "商品" + byId.getGoodsName() + "企叮咚库已下架");
                    }
                }
                //壹邦玖
                if (byId.getThirdPartyPlatformId() != null && Integer.valueOf(1).equals(byId.getThirdPartyPlatformType())) {
                    List<Integer> goodsIdList = new ArrayList<>();
                    goodsIdList.add(Integer.valueOf(byId.getThirdPartyPlatformId()));
                    List<com.alibaba.fastjson.JSONObject> platformGoodsDetail = goodsService.getPlatformGoodsDetail(goodsIdList);
                    List<Goods> goodsList = new ArrayList<>();
                    goodsList.add(byId);
                    Map<String, List> goodsSkusConversion = goodsService.goodsSkusConversion(platformGoodsDetail, goodsList);
                    List<GoodsSku> goodsSkuList = (List<GoodsSku>) goodsSkusConversion.get("goods_sku");
                    for (GoodsSku sku : goodsSkuList) {
                        if (Integer.valueOf(0).equals(sku.getIs_display())) {
                            throw new ServiceException(ResultCode.PARAMS_ERROR, "商品" + byId.getGoodsName() + "壹邦玖库已下架");
                        }
                    }
                }
                //盛创汇联
                if (byId.getThirdPartyPlatformId() != null && Integer.valueOf(3).equals(byId.getThirdPartyPlatformType())) {
                    //商品全量/选品库查询
                    ArrayList<Long> arrayList = new ArrayList<>();
                    arrayList.add(Long.parseLong(byId.getThirdPartyPlatformId()));

                    ListGoodsRes.Query query = new ListGoodsRes.Query();
                    query.setGoodsIds(arrayList);
                    query.setQueryType("1");

                    ListGoodsRes listGoodsRes = new ListGoodsRes();
                    listGoodsRes.setQuery(query);
                    try {
                        ListGoodsReps listGoodsReps = xdxtGoodsService.goodsList(listGoodsRes);
                        if(listGoodsReps.getResult().getRecords() == null || listGoodsReps.getResult().getRecords().isEmpty()){
                            throw new ServiceException(ResultCode.PARAMS_ERROR, "商品" + byId.getGoodsName() + "盛创汇联已下架");
                        }
                    } catch (JsonProcessingException ex) {
                        throw new RuntimeException(ex);
                    }
                }
            });
        }
    }

    /**
     * 检查商品是否可更新状态
     *
     * @param params 更新商品状态参数
     */
    private void checkUpdateGoodsStatusAvailable(GoodsUpdateStatusDTO params) {
        if (CollUtil.isEmpty(params.getGoodsIds()) && CharSequenceUtil.isEmpty(params.getStoreId())) {
            throw new ServiceException(ResultCode.PARAMS_ERROR, "更新ID为空");
        }
        List<Goods> goodsList = Lists.newArrayList();
        if (null == params.getGoodsIds() || params.getGoodsIds().isEmpty()) {
            LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Goods::getStoreId, params.getStoreId());
            goodsList = goodsService.list(queryWrapper);
        } else {
            goodsList = this.goodsService.listByIds(params.getGoodsIds());
        }
        //List<Goods> goodsList = this.goodsService.listByIds(params.getGoodsIds());
        for (Goods goods : goodsList) {
            // 商品上架
            if (GoodsMarketEnum.UPPER.name().equals(params.getGoodsStatus())) {
                // 代理商品，且是商家端
                if (goods.getIsProxyGoods() &&
                        SceneEnums.STORE.equals(Objects.requireNonNull(UserContext.getCurrentUser()).getScene()) &&
                        CharSequenceUtil.isNotEmpty(goods.getSupplierGoodsId())) {
                    // 获取供应商商品
                    Goods supplierGoods = goodsService.getById(goods.getSupplierGoodsId());
                    if (null == supplierGoods) {
                        throw new ServiceException(ResultCode.GOODS_ERROR);
                    }
                    // 供应商商品是上架状态，且审核通过，商家才能上架代理商品
                    if (!GoodsMarketEnum.UPPER.name().equals(supplierGoods.getMarketEnable()) ||
                            !GoodsAuthEnum.PASS.name().equals(supplierGoods.getAuthFlag())) {
                        throw new ServiceException(ResultCode.GOODS_UPPER_ERROR_BY_SUPPLIER);
                    }
                }
            }

            LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
            categoryLambdaQueryWrapper.in(Category::getId, Arrays.asList(goods.getCategoryPath().split(",")));
            categoryLambdaQueryWrapper.eq(Category::getDeleteFlag, false);
            if (categoryService.count() < 3) {
                throw new ServiceException(ResultCode.CATEGORY_NEED_EXIST);
            }
            if (CharSequenceUtil.isNotEmpty(goods.getBrandId())) {
                LambdaQueryWrapper<Brand> brandLambdaQueryWrapper = new LambdaQueryWrapper<>();
                brandLambdaQueryWrapper.eq(Brand::getId, goods.getBrandId());
                brandLambdaQueryWrapper.eq(Brand::getDeleteFlag, false);
                if (brandService.count() < 1) {
                    throw new ServiceException(ResultCode.BRAND_NEED_EXIST);
                }
            }
            //判断是否为免税商品,给免税商品的店铺分类增加商品数量标识
            log.info("#checkUpdateGoodsStatusAvailable# 上下架状态,维护上下架,goods:{},params:{}", com.alibaba.fastjson.JSONObject.toJSONString(goods), com.alibaba.fastjson.JSONObject.toJSONString(params));

            //上架或者审核商品维护其分类的商品数量
            if ((StrUtil.isNotEmpty(params.getGoodsStatus())
                    && params.getGoodsStatus().equals(GoodsMarketEnum.UPPER.name()))
                    || (StrUtil.isNotEmpty(params.getGoodsAuth()) && params.getGoodsAuth().equals(GoodsAuthEnum.PASS.name()) && StrUtil.isNotEmpty(goods.getStoreCategoryPath()))
                    && goods.getIsFree() != null && goods.getIsFree()
                    && StrUtil.isNotEmpty(goods.getStoreCategoryPath())) {
                this.updateGoodsRedisStoreCategory(goods, StrUtil.isNotEmpty(params.getGoodsStatus()) ? params.getGoodsStatus() : goods.getMarketEnable(), StrUtil.isNotEmpty(params.getGoodsAuth()) ? params.getGoodsAuth() : goods.getAuthFlag());
            }
        }
    }

    /**
     * 处理店铺类目
     * @param goods
     * @param
     */
    private void updateGoodsRedisStoreCategory(Goods goods, String goodsStatus, String authStatus) {
        log.info("#updateGoodsRedisStoreCategory# 处理店铺类目下的商品数量,storeCategoryId:{}, goodsStatus:{},authStatus:{}", goods.getStoreCategoryPath(), goodsStatus, authStatus);
        Double num = 0d;
        //上架状态,审核状态
        boolean marketStatusFlag = false, authStatusFlag = false;
        //上架状态
        if (goods.getMarketEnable().equals(GoodsMarketEnum.UPPER.name()) || goodsStatus.equals(GoodsMarketEnum.UPPER.name())) {
            marketStatusFlag = true;
        }
        //审核状态
        if (goods.getAuthFlag().equals(GoodsAuthEnum.PASS.name()) || authStatus.equals(GoodsAuthEnum.PASS.name())) {
            authStatusFlag = true;
        }
        //上架状态
        if (goods.getAuthFlag().equals(GoodsAuthEnum.PASS.name()) && goods.getMarketEnable().equals(GoodsMarketEnum.UPPER.name())
                && (!authStatus.equals(GoodsAuthEnum.PASS.name()) || !goodsStatus.equals(GoodsMarketEnum.UPPER.name()))) {
            marketStatusFlag = false;
        }

        if (marketStatusFlag && authStatusFlag) {
            //上架或者审核商品
            num = 1.0;
        } else {
            //删除商品
            num = -1.0;
        }
        log.info("#updateGoodsRedisStoreCategory# 处理店铺类目下的商品数量,num:{}", num);
        if (StringUtils.isNotEmpty(goods.getStoreCategoryPath())) {
            String[] storeCategory = goods.getStoreCategoryPath().split(",");
            Double redisNum = cache.increment(CommonConstant.STORE_CATEGORY_NUM + storeCategory[0], num, null, null, false);
            log.info("#updateGoodsRedisStoreCategory# 处理店铺类目下的商品数量,redisNum:{}", redisNum);
            log.info("#checkUpdateGoodsStatusAvailable# 上下架状态,维护上下架 , 店铺分类id:{},redis分类下的商品数量:{}", storeCategory[0], redisNum);
            if (redisNum < 0) {
                cache.remove(CommonConstant.STORE_CATEGORY_NUM + storeCategory[0]);
            }
        }
    }

    /**
     * 执行更新商品状态
     *
     * @param params 更新商品状态参数
     * @return 是否更新成功
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean executeGoodsStatusUpdate(GoodsUpdateStatusDTO params) {
        //待清除缓存的key
        List<String> cacheKeys = new ArrayList<>();

        // 更新商品
        LambdaUpdateWrapper<Goods> updateGoodsWrapper = new LambdaUpdateWrapper<>();
        LambdaUpdateWrapper<GoodsSku> updateGoodsSkuWrapper = new LambdaUpdateWrapper<>();
        if (CharSequenceUtil.isNotEmpty(params.getGoodsAuth())) {
            updateGoodsWrapper.set(Goods::getAuthFlag, GoodsAuthEnum.valueOf(params.getGoodsAuth()).name());
            updateGoodsSkuWrapper.set(GoodsSku::getAuthFlag, params.getGoodsAuth());
        }
        if (CharSequenceUtil.isNotEmpty(params.getGoodsStatus())) {
            updateGoodsWrapper.set(Goods::getMarketEnable, GoodsMarketEnum.valueOf(params.getGoodsStatus()).name());
            updateGoodsSkuWrapper.set(GoodsSku::getMarketEnable, params.getGoodsStatus());
        }
        updateGoodsWrapper.set(CharSequenceUtil.isNotEmpty(params.getUnderReason()), Goods::getUnderMessage, params.getUnderReason());
        updateGoodsWrapper.set(params.getDeleteFlag() != null, Goods::getDeleteFlag, params.getDeleteFlag());
        updateGoodsSkuWrapper.set(params.getDeleteFlag() != null, GoodsSku::getDeleteFlag, params.getDeleteFlag());
        updateGoodsSkuWrapper.set(CharSequenceUtil.isNotEmpty(params.getUnderReason()), GoodsSku::getUnderMessage, params.getUnderReason());


        if (!SceneEnums.URBAN_SUBSTATION.equals(Objects.requireNonNull(UserContext.getCurrentUser()).getScene())) {
            if (CharSequenceUtil.isNotEmpty(params.getStoreId())) {
                updateGoodsWrapper.nested(i -> i.eq(Goods::getStoreId, params.getStoreId()).or()
                        .eq(Goods::getSupplierId, params.getStoreId()));
                updateGoodsSkuWrapper.nested(i -> i.eq(GoodsSku::getStoreId, params.getStoreId()).or()
                        .eq(GoodsSku::getSupplierId, params.getStoreId()));
            } else {
                updateGoodsWrapper.eq(CharSequenceUtil.isNotEmpty(params.getStoreId()), Goods::getStoreId, params.getStoreId());
                updateGoodsSkuWrapper.eq(CharSequenceUtil.isNotEmpty(params.getStoreId()), GoodsSku::getStoreId, params.getStoreId());
            }
        }

        if (CollUtil.isNotEmpty(params.getGoodsIds())) {
            // 如果是上架商品，且是供应商商品，则只上架供应商商品，不上架店铺代理商品
            if (GoodsMarketEnum.UPPER.name().equals(params.getGoodsStatus())) {
                updateGoodsWrapper.nested(i -> i.in(Goods::getId, params.getGoodsIds()));
                updateGoodsSkuWrapper.nested(i -> i.in(GoodsSku::getGoodsId, params.getGoodsIds()));
            } else {
                updateGoodsWrapper.nested(i -> i.in(Goods::getId, params.getGoodsIds()).or()
                        .in(Goods::getSupplierGoodsId, params.getGoodsIds()));
                updateGoodsSkuWrapper.nested(i -> i.in(GoodsSku::getGoodsId, params.getGoodsIds()).or()
                        .in(GoodsSku::getSupplierGoodsId, params.getGoodsIds()));
            }
        } else {
            updateGoodsWrapper.in(CollUtil.isNotEmpty(params.getGoodsIds()), Goods::getId, params.getGoodsIds());
            updateGoodsSkuWrapper.in(CollUtil.isNotEmpty(params.getGoodsIds()), GoodsSku::getGoodsId, params.getGoodsIds());
        }
        boolean result = this.goodsService.update(updateGoodsWrapper);

        //操作商品缓存key
        if (params.getGoodsIds() != null && !params.getGoodsIds().isEmpty()) {
            params.getGoodsIds().forEach(i -> cacheKeys.add(CachePrefix.GOODS.getPrefix() + i));
        }
        //清除缓存
        cache.multiDel(cacheKeys);

        boolean update = this.goodsSkuService.update(updateGoodsSkuWrapper);

        if (StringUtils.isNotEmpty(params.getGoodsAuth()) && params.getGoodsAuth().equals("PASS")) {
            for (String goodsId : params.getGoodsIds()) {
                LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(Goods::getSupplierGoodsId, goodsId);
                List<Goods> goodsList = goodsService.list(queryWrapper);

                Goods supplerGoods = goodsService.getById(goodsId);
                if (!goodsList.isEmpty()) {
                    goodsList.stream().forEach(goods1 -> {
                        //删除店铺原有sku， 把供应商的sku同步过去
                        List<GoodsSku> goodsSkuList = goodsSkuService.list(new LambdaQueryWrapper<GoodsSku>().eq(GoodsSku::getGoodsId, goodsId));
                        List<GoodsSku> goodsSkus = this.storeOwnHandler(goodsSkuList, goods1);
                        LambdaUpdateWrapper<GoodsSku> goodsSkuLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                        goodsSkuLambdaUpdateWrapper.eq(GoodsSku::getGoodsId, goods1.getId());
                        goodsSkuLambdaUpdateWrapper.set(GoodsSku::getDeleteFlag, true);

                        goods1.setPrice(supplerGoods.getPrice());
                        goodsService.updateById(goods1);
                        goodsSkuService.update(goodsSkuLambdaUpdateWrapper);

                        goodsSkuService.saveBatch(goodsSkus);
//                    //删除sku相册
//                    this.goodsGalleryService.removeByGoodsId(goods1.getId());
//                    // 添加商品图片
//                    this.goodsGalleryService.add(goodsOperationDTO.getGoodsGalleryList(), goods1.getId());
                    });
                }
            }
        }

        return result && update;
    }


    /**
     * 发送更新商品状态消息
     *
     * @param params 更新商品状态参数
     */
    @Transactional(rollbackFor = Exception.class)
    public void sendGoodsStatusUpdateMessage(GoodsUpdateStatusDTO params) {
        // 状态是否为通过
        boolean updateAuth = CharSequenceUtil.isNotEmpty(params.getGoodsAuth()) && GoodsAuthEnum.PASS.name().equals(params.getGoodsAuth());
        // 状态是否为上架
        boolean updateStatus =
                CharSequenceUtil.isNotEmpty(params.getGoodsStatus()) && GoodsMarketEnum.UPPER.name().equals(params.getGoodsStatus());
        if (updateAuth || updateStatus) {
            // 如果状态为上架或审核通过则生成商品
            this.generatorGoods(CollUtil.isNotEmpty(params.getGoodsIds()) ? params.getGoodsIds() : null,
                    CharSequenceUtil.isNotEmpty(params.getStoreId()) ? params.getStoreId() : null);
        } else {
            // 如果为其他状态，则清除商品信息
            if (CollUtil.isNotEmpty(params.getGoodsIds())) {
                this.cleanGoods(params.getGoodsIds());
            } else if (CharSequenceUtil.isNotEmpty(params.getStoreId())) {
                List<String> goodsIds =
                        this.goodsService.queryListIdByParams(GoodsSearchParams.builder().storeAndSupplierId(params.getStoreId()).build());
                if (!goodsIds.isEmpty()) {
                    this.cleanGoods(goodsIds);
                }
            }
        }
    }

    @Override
    @Transactional
    @ShardingTransactionType(TransactionType.BASE)
    public void underStoreGoods(String storeId) {
        this.updateGoodsStatus(GoodsUpdateStatusDTO.builder().storeId(storeId).goodsStatus(GoodsMarketEnum.DOWN.name()).underReason("店铺关闭").build());
    }

    @Override
    @Transactional
    @ShardingTransactionType(TransactionType.BASE)
    public void updateStoreDetail(Store store) {
        UpdateWrapper updateWrapper = new UpdateWrapper<>().eq("store_id", store.getId()).set("store_name", store.getStoreName()).set(
                "self_operated", store.getSelfOperated());
        this.goodsService.update(updateWrapper);
        this.goodsSkuService.update(updateWrapper);
        cache.vagueDel(CachePrefix.GOODS_SKU.getPrefix());
    }

    @Override
    public GoodsVO getGoodsVO(String goodsId) {
        //缓存获取，如果没有则读取缓存
        GoodsVO goodsVO = null;//(GoodsVO) cache.get(CachePrefix.GOODS.getPrefix() + goodsId);
        if (goodsVO != null) {
            // 获取商品店铺
            if (CharSequenceUtil.isEmpty(goodsVO.getStoreId())) {
                Goods goods = this.goodsService.getById(goodsId);
                goodsVO.setStoreId(goods.getStoreId());
            }
            return goodsVO;
        }
        //查询商品信息
        Goods goods = this.goodsService.getById(goodsId);
        if (goods == null) {
            log.error("商品ID为" + goodsId + "的商品不存在");
            throw new ServiceException(ResultCode.GOODS_NOT_EXIST);
        }
        goodsVO = new GoodsVO();
        //赋值
        BeanUtils.copyProperties(goods, goodsVO);
        //商品id
        goodsVO.setId(goods.getId());
        goodsVO.setStoreId(goods.getStoreId());
        //商品相册赋值
        List<String> images = new ArrayList<>();
        List<GoodsGallery> galleryList = goodsGalleryService.goodsGalleryList(goodsId);
        for (GoodsGallery goodsGallery : galleryList) {
            images.add(goodsGallery.getOriginal());
        }
        goodsVO.setGoodsGalleryList(images);
        //商品sku赋值
        GoodsSearchParams goodsSearchParams = new GoodsSearchParams();
        goodsSearchParams.setGoodsId(goodsId);
        List<GoodsSkuVO> goodsListByGoodsId = goodsSkuService.getGoodsListByGoodsId(goodsSearchParams);
        if (goodsListByGoodsId != null && !goodsListByGoodsId.isEmpty()) {
            goodsVO.setSkuList(goodsListByGoodsId);
        }
        //商品分类名称赋值
        List<String> categoryName = new ArrayList<>();
        String categoryPath = goods.getCategoryPath();
        if (CharSequenceUtil.isNotEmpty(categoryPath)) {
            String[] strArray = categoryPath.split(",");
            List<Category> categories = categoryService.listByIds(Arrays.asList(strArray));
            for (Category category : categories) {
                categoryName.add(category.getName());
            }
            goodsVO.setCategoryName(categoryName);
        }

        //参数非空则填写参数
        if (CharSequenceUtil.isNotEmpty(goods.getParams())) {
            goodsVO.setGoodsParamsDTOList(JSONUtil.toList(goods.getParams(), GoodsParamsDTO.class));
        }

        //供应商商品，且支持采购，则描述采购规则
        if (SceneEnums.SUPPLIER.name().equals(goods.getScene()) && goods.getSupportPurchase()) {
            List<Wholesale> wholesaleList = wholesaleService.findByGoodsId(goodsId);
            if (CollUtil.isNotEmpty(wholesaleList)) {
                goodsVO.setWholesaleList(wholesaleList);
            }
        }

        FreightTemplateVO freightTemplate = freightTemplateClient.getFreightTemplate(goodsVO.getTemplateId());
        if (freightTemplate != null) {
            goodsVO.setFreightTemplate(freightTemplate);
        }
        if (StringUtils.isNotEmpty(goodsVO.getPackId())) {
            PackConfigVO packConfigVO = packConfigClient.getById(goodsVO.getPackId());
            if (packConfigVO != null) {
                goodsVO.setPackConfig(packConfigVO);
            }
        }
        cache.put(CachePrefix.GOODS.getPrefix() + goodsId, goodsVO);
        return goodsVO;
    }

    @Override
    @Transactional
    @ShardingTransactionType(TransactionType.BASE)
    public void updateGoodsSkuCommentNum(String skuId) {
        GoodsSku goodsSku = this.goodsSkuService.getGoodsSkuByIdFromCache(skuId);
        if (goodsSku == null) {
            return;
        }
        String goodsId = goodsSku.getGoodsId();
        //获取商品信息
        Goods goods = this.goodsService.getById(goodsId);
        if (goods == null) {
            return;
        }
        //修改商品评价数量
        long commentNum = memberEvaluationClient.getEvaluationCount(EvaluationQueryParams.builder().status(SwitchEnum.OPEN.name()).goodsId(goodsId).build());
        goods.setCommentNum((int) commentNum);

        //好评数量
        //long highPraiseNum = memberEvaluationClient.getEvaluationCount(EvaluationQueryParams.builder().status(SwitchEnum.OPEN.name()).grade(EvaluationGradeEnum.GOOD.name()).skuId(goodsSku.getId()).build());


        long highPraiseNum = memberEvaluationClient.getEvaluationCount(EvaluationQueryParams.builder().status(SwitchEnum.OPEN.name()).goodsId(goodsId).grade(EvaluationGradeEnum.GOOD.name()).build());
        //好评率
//        double grade = NumberUtil.mul(NumberUtil.div(highPraiseNum, goodsSku.getCommentNum().doubleValue(), 2), 100);
//        goodsSku.setGrade(grade);
        //修改规格
        //this.goodsSkuService.updateGoodsSkuGrade(skuId, grade, goodsSku.getCommentNum());
        double grade = NumberUtil.mul(NumberUtil.div(highPraiseNum, goods.getCommentNum().doubleValue(), 2), 100);
        goods.setGrade(grade);
        LambdaUpdateWrapper<Goods> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.set(Goods::getCommentNum, goods.getCommentNum());
        updateWrapper.set(Goods::getGrade, goods.getGrade());
        updateWrapper.eq(Goods::getId, goodsId);
        this.goodsService.update(updateWrapper);

        //修改商品的评价数量
        goodsService.updateGoodsCommentNum(goodsSku.getGoodsId());
        cache.remove(CachePrefix.GOODS.getPrefix() + goodsId);
        cache.remove(GoodsSkuService.getCacheKeys(skuId));

        this.goodsSkuService.updateGoodsSkuGrade(goodsId, grade, goods.getCommentNum());

        //修改规格索引,发送mq消息
        Map<String, Object> updateIndexFieldsMap = EsIndexUtil.getUpdateIndexFieldsMap(MapUtil.builder(new HashMap<String, Object>()).put("goodsId", goodsId).build(), MapUtil.builder(new HashMap<String, Object>()).put("commentNum", goods.getCommentNum()).put("highPraiseNum", highPraiseNum).put("grade", grade).build());
        applicationEventPublisher.publishEvent(TransactionCommitSendMQEvent.builder()
                .source("更新商品评价数量")
                .exchange(amqpExchangeProperties.getGoods())
                .routingKey(GoodsRoutingKey.UPDATE_GOODS_INDEX_FIELD)
                .message(JSONUtil.toJsonStr(updateIndexFieldsMap))
                .build());
    }

    @Override
    public Map<String, Object> getGoodsSkuDetail(String goodsId, String skuId, String distId) {
        log.info("footPrint-input--->{}", goodsId);
        Map<String, Object> map = new HashMap<>(16);
        AuthUser currentUser = UserContext.getCurrentUser();
        //获取商品VO
        GoodsVO goodsVO = this.getGoodsVO(goodsId);
        //如果skuid为空，则使用商品VO中sku信息获取
        if (CharSequenceUtil.isEmpty(skuId) || "undefined".equals(skuId)) {
            // 使用匿名Comparator类对列表进行排序
            Collections.sort(goodsVO.getSkuList(), Comparator.comparingDouble(GoodsSku::getPrice));
            skuId = goodsVO.getSkuList().get(0).getId();
        }
        //从缓存拿商品Sku
        GoodsSku goodsSku = this.goodsSkuService.getGoodsSkuByIdFromCache(skuId);
        //如果使用商品ID无法查询SKU则返回错误
        if (goodsVO == null || goodsSku == null) {
            throw new ServiceException(ResultCode.GOODS_NOT_EXIST);
        }

        //商品下架||商品未审核通过||商品删除，则提示：商品已下架
        if (GoodsMarketEnum.DOWN.name().equals(goodsVO.getMarketEnable()) || !GoodsAuthEnum.PASS.name().equals(goodsVO.getAuthFlag()) || Boolean.TRUE.equals(goodsVO.getDeleteFlag())) {
            throw new ServiceException(ResultCode.GOODS_NOT_EXIST);
        }

        //获取当前商品的索引信息
        //EsGoodsIndex goodsIndex = this.goodsIndexService.findEsGoodsIndexById(skuId);

        //商品规格
        List<GoodsGallery> goodsGalleriesS = goodsGalleryService.list(new LambdaQueryWrapper<GoodsGallery>().in(GoodsGallery::getGoodsId, goodsSku.getGoodsId()));
        GoodsSkuVO goodsSkuDetail = this.goodsSkuService.getGoodsSkuVO(goodsSku, goodsGalleriesS);
        //设置规格参数
        goodsSkuDetail.setSpecParameter(goodsVO.getSpecParameter());

        //生成sku的临时esIndex,该esIndex不会写es库
        //同时也是解决移动端商品出现多规格数据的问题
        EsGoodsIndex goodsIndex = this.goodsIndexService.createTempData(goodsSku);

        Map<String, Object> promotionMap = new HashMap<>();

        if(goodsIndex != null) {
            promotionMap = goodsIndex.getPromotionMap();
            //设置当前商品的促销价格
            if (promotionMap != null && !promotionMap.isEmpty()) {
                promotionMap = promotionMap.entrySet().stream().parallel().filter(i -> {
                    JSONObject jsonObject = JSONUtil.parseObj(i.getValue());
                    if (i.getKey().contains(PromotionTypeEnum.COUPON.name()) && currentUser != null) {
                        Integer couponLimitNum = jsonObject.getInt("couponLimitNum");
                        Coupon coupon = promotionsClient.getCouponById(jsonObject.getStr("id"));
                        if (coupon == null || (coupon.getPublishNum() != 0 && coupon.getReceivedNum() >= coupon.getPublishNum())) {
                            return false;
                        }
                        if (couponLimitNum > 0) {
                            Long count = memberCouponClient.getMemberCouponCount(currentUser.getExtendId(), jsonObject.getStr(
                                    "id"));
                            if (count >= couponLimitNum) {
                                return false;
                            }
                        }
                    }
                    // 过滤活动赠送优惠券和无效时间的活动
                    return (jsonObject.get("getType") == null || jsonObject.get("getType", String.class).equals(CouponGetEnum.FREE.name())) && (jsonObject.get("startTime") != null && jsonObject.get("startTime", Date.class).getTime() <= System.currentTimeMillis()) && (jsonObject.get("endTime") == null || jsonObject.get("endTime", Date.class).getTime() >= System.currentTimeMillis());
                }).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

                Optional<Map.Entry<String, Object>> containsPromotion =
                        promotionMap.entrySet().stream().filter(i -> i.getKey().contains(PromotionTypeEnum.SECKILL.name()) || i.getKey().contains(PromotionTypeEnum.PINTUAN.name())).findFirst();
                if (containsPromotion.isPresent()) {
                    JSONObject jsonObject = JSONUtil.parseObj(containsPromotion.get().getValue());
                    PromotionGoodsSearchParams searchParams = new PromotionGoodsSearchParams();
                    searchParams.setSkuId(skuId);
                    searchParams.setPromotionId(jsonObject.get("id").toString());
                    PromotionGoods promotionsGoods = promotionGoodsClient.getPromotionsGoods(searchParams);
                    if (promotionsGoods != null && promotionsGoods.getPrice() != null) {
                        goodsSkuDetail.setPromotionFlag(true);
                        goodsSkuDetail.setPromotionPrice(promotionsGoods.getPrice());
                        goodsSkuDetail.setPromotionOriginalPrice(promotionsGoods.getOriginalPrice());
                    }
                } else {
                    goodsSkuDetail.setPromotionFlag(false);
                    goodsSkuDetail.setPromotionPrice(null);
                }

            }
        }

//        System.out.println(goodsSkuDetail);
        System.out.println(goodsSkuDetail.getMaxfNumber());
        //处理图片
        if(StringUtils.isNotEmpty(goodsSkuDetail.getThumbnail())){
            goodsSkuDetail.setThumbnail(goodsSkuDetail.getThumbnail().split("\\?")[0]);
        }
        if(goodsSkuDetail.getGoodsGalleryList()!=null&&goodsSkuDetail.getGoodsGalleryList().size()>0){
            List<String> collect = goodsSkuDetail.getGoodsGalleryList().stream().map(e -> {
                e = e.split("\\?")[0];
                return e;
            }).collect(Collectors.toList());
            goodsSkuDetail.setGoodsGalleryList(collect);
        }

        //查询自己买省*钱，立即推广赚*钱
        initSetting();
        if (null != currentUser) {
            Distribution currentDistribution = distributionClient.getDistribution(UserContext.getCurrentId());
            goodsSkuDetail.initOmitGreenScore(currentDistribution,goodsSkuDetail,settings);
        }


        map.put("data", goodsSkuDetail);

        //获取分类
        map.put("wholesaleList",
                SalesModeEnum.PURCHASING.name().equals(goodsVO.getSalesModel()) || SalesModeEnum.WHOLESALE.name().equals(goodsVO.getSalesModel()) ?
                        wholesaleService.findByGoodsId(goodsSkuDetail.getGoodsId()) : Collections.emptyList());
        map.put("categoryName", CharSequenceUtil.isNotEmpty(goodsIndex.getCategoryNamePath()) ? goodsIndex.getCategoryNamePath().split(",") :
                null);

        //获取规格信息
        map.put("specs", this.groupBySkuAndSpec(goodsVO.getSkuList()));
        map.put("promotionMap", promotionMap);

        //获取参数信息
        if (goodsVO.getGoodsParamsDTOList() != null && !goodsVO.getGoodsParamsDTOList().isEmpty()) {
            map.put("goodsParamsDTOList", goodsVO.getGoodsParamsDTOList());
        }

        //记录用户足迹
        if (currentUser != null && currentUser.getScene() != null) {
            String userId = currentUser.getExtendId();
            FootPrint footPrint = new FootPrint(userId, goodsId, skuId, goodsVO.getStoreId(), new Date());
            log.info("footPrint--->{}", com.alibaba.fastjson.JSONObject.toJSONString(footPrint));
            amqpSender.send(AmqpMessage.builder().exchange(amqpExchangeProperties.getGoods()).routingKey(GoodsRoutingKey.VIEW_GOODS).message(footPrint).build());
        }

        //绑定分销员的上下级关系
        if (currentUser != null && StringUtils.isNotEmpty(distId)) {
            this.bindParent(currentUser, distId, goodsId);
        }
        return map;
    }

    /**
     * 绑定上下级关系
     */
    private void bindParent(AuthUser currentUser, String distId, String goodsId) {
        //推广店主
        Distribution distribution = distributionClient.getDistributionById(distId);
        //当前人店主
        Distribution currentDistribution = distributionClient.getDistribution(UserContext.getCurrentId());
        User user = userClient.getById(currentUser.getId());
        //自己点击，自己的分享链接不做操作
        if (distribution != null && currentDistribution != null && distribution.getId().equals(currentDistribution.getId())) {
            return;
        }
        //未获取到数据，不做操作
        if (distribution == null || StringUtils.isEmpty(distribution.getId())) {
            return;
        }
        //原绑定关系代码
/*        if (user != null && StringUtils.isNotEmpty(user.getId()) && StringUtils.isEmpty(user.getParentId())) {
            user.setId(UserContext.getCurrentId());
            user.setParentId(distribution.getMemberId());
            user.setParentUsername(distribution.getMemberName());
            userClient.updateById(user);
        }
        //如果当前，购买用户是店主。当前商品的分销员，设置成店主上级
        log.info("user == {}", com.alibaba.fastjson.JSONObject.toJSONString(user));
        log.info("currentDistribution == {}", com.alibaba.fastjson.JSONObject.toJSONString(currentDistribution));
        log.info("distribution == {}", com.alibaba.fastjson.JSONObject.toJSONString(distribution));
        if (user != null && currentDistribution != null && StringUtils.isNotEmpty(currentDistribution.getId()) && StringUtils.isEmpty(currentDistribution.getParentId())) {
            Distribution dis = new Distribution();
            dis.setMemberId(user.getId());
            dis.setParentId(distribution.getMemberId());
            dis.setParentUsername(distribution.getMemberName());
            log.info("dis == {}", com.alibaba.fastjson.JSONObject.toJSONString(dis));
            distributionClient.updateDistributionParentInfo(dis);
        }*/

        if (user != null && StringUtils.isNotEmpty(user.getId()) && StringUtils.isEmpty(user.getParentId())) {
            user.setId(UserContext.getCurrentId());
            user.setParentId(distribution.getMemberId());
            user.setParentUsername(distribution.getMemberName());
//          userClient.updateById(user);

            //如果当前，购买用户是店主。当前商品的分销员，设置成店主上级
            log.info("user == {}", com.alibaba.fastjson.JSONObject.toJSONString(user));
            log.info("currentDistribution == {}", com.alibaba.fastjson.JSONObject.toJSONString(currentDistribution));
            log.info("distribution == {}", com.alibaba.fastjson.JSONObject.toJSONString(distribution));

            Distribution dis = new Distribution();
            dis.setMemberId(user.getId());
            dis.setParentId(distribution.getMemberId());
            dis.setParentUsername(distribution.getMemberName());
            log.info("dis == {}", com.alibaba.fastjson.JSONObject.toJSONString(dis));
//          distributionClient.updateDistributionParentInfo(dis);
            //缓存24小时,上下级关系临时记录到redis缓存
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("userId", user.getId());
            jsonObject.put("parentId", user.getParentId());
            jsonObject.put("parentUserName", user.getParentUsername());
            jsonObject.put("goodsId", goodsId);
            cache.put(CommonConstant.TEMP_SHARE_GOODS_PARENT_KEY + user.getId() + goodsId, jsonObject.toString(), 365L, TimeUnit.DAYS);
            cache.put(CommonConstant.TEMP_SHARE_GOODS_PARENT_KEY + user.getId(), CommonConstant.TEMP_SHARE_GOODS_PARENT_KEY + user.getId() + goodsId, 365L, TimeUnit.DAYS);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @ShardingTransactionType(TransactionType.BASE)
    public Boolean deleteGoods(List<String> goodsIds, String storeId) {
        Assert.notEmpty(goodsIds, "商品ID不能为空");


        // 修改规格商品
        LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CharSequenceUtil.isNotEmpty(storeId), Goods::getStoreId, storeId);
        queryWrapper.nested(s -> s.in(Goods::getId, goodsIds).or().in(Goods::getSupplierGoodsId, goodsIds));
        List<Goods> goodsList = this.goodsService.list(queryWrapper);
        List<String> goodsCacheKeys = new ArrayList<>();
        for (Goods goods : goodsList) {
            // 修改SKU状态
            goodsSkuService.updateGoodsSkuStatus(goods);
            goodsCacheKeys.add(CachePrefix.GOODS.getPrefix() + goods.getId());
            //维护店铺分类id下的数量
            if (goods.getIsFree() != null && goods.getIsFree() && StrUtil.isNotEmpty(goods.getStoreCategoryPath())) {
                this.updateGoodsRedisStoreCategory(goods, GoodsMarketEnum.DOWN.name(), GoodsMarketEnum.DOWN.name());
            }
        }
        LambdaUpdateWrapper<Goods> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(Goods::getMarketEnable, GoodsMarketEnum.DOWN.name());
        updateWrapper.set(Goods::getDeleteFlag, true);
        updateWrapper.eq(CharSequenceUtil.isNotEmpty(storeId), Goods::getStoreId, storeId);
        updateWrapper.nested(s -> s.in(Goods::getId, goodsIds).or().in(Goods::getSupplierGoodsId, goodsIds));
        this.goodsService.update(updateWrapper);
        // 删除缓存
        cache.multiDel(goodsCacheKeys);
        return true;
    }

    @Override
    public Boolean deleteGoodsV2(List<String> goodsIds, String storeId) {
        //删除拼团和秒杀商品,红包商品,积分商品
        this.removeGoods(goodsIds);
        // 发送删除es商品的信息
        ThreadPoolUtil.getPool().execute(()-> amqpSender.send(AmqpMessage.builder()
                .exchange(amqpExchangeProperties.getGoods())
                .routingKey(GOODS_DELETE)
                .message(goodsIds)
                .build()));
        try {
            Thread.sleep(3000);
            deleteGoods(goodsIds,storeId);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        return true;
    }

    @Override
    @Transactional
    @ShardingTransactionType(TransactionType.BASE)
    public Boolean downGoodsByCategoryId(String categoryId, String underReason) {
        //修改规格商品
        LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(Goods::getId);
        queryWrapper.like(Goods::getCategoryPath, categoryId);
        List<Goods> goodsList = this.goodsService.list(queryWrapper);

        if (CollUtil.isEmpty(goodsList)) {
            return true;
        }
        GoodsUpdateStatusDTO goodsUpdateStatusDTO = new GoodsUpdateStatusDTO();
        goodsUpdateStatusDTO.setGoodsIds(goodsList.stream().map(Goods::getId).toList());
        goodsUpdateStatusDTO.setUnderReason(underReason);
        goodsUpdateStatusDTO.setGoodsStatus(GoodsMarketEnum.DOWN.name());
        return this.updateGoodsStatus(goodsUpdateStatusDTO);
    }

    @Override
    @Transactional
    @ShardingTransactionType(TransactionType.BASE)
    public void editProxyGoods(ProxyGoodsOperationDTO proxyGoodsOperationDTO) {
        // 校验商品是否存在
        log.info("proxyGoodsOperationDTO1212=== {}", com.alibaba.fastjson.JSONObject.toJSONString(proxyGoodsOperationDTO));
        Goods goods = this.goodsService.getById(proxyGoodsOperationDTO.getGoodsId());
        if (goods == null) {
            throw new ServiceException(ResultCode.GOODS_NOT_EXIST);
        }
        // 校验商品是否是代理商品
        if (Boolean.FALSE.equals(goods.getIsProxyGoods())) {
            throw new ServiceException(ResultCode.NORMAL_GOODS_CANT_UPDATE_HEAR);
        }
        // 校验商品是否是自己的商品
        if (!goods.getStoreId().equals(UserContext.getCurrentUser().getExtendId())) {
            throw new ServiceException();
        }

        //将商品可编辑的参数复制给商品本身
        log.info("goodsgetIsVipGoods", goods.getIsVipGoods());
        BeanUtils.copyProperties(proxyGoodsOperationDTO, goods);
        log.info("endIsVipGoods", goods.getIsVipGoods());
        goods.setIsGreenGoods(proxyGoodsOperationDTO.getIsGreenGoods());
        goods.setIsCommonwealGoods(proxyGoodsOperationDTO.getIsCommonwealGoods());
        goods.setIsVipGoods(proxyGoodsOperationDTO.getIsVipGoods());
        goods.setIsGreenSecurities(proxyGoodsOperationDTO.getIsGreenSecurities());
        goods.setIsTicket(proxyGoodsOperationDTO.getIsTicket());
        goods.setIsMeal(proxyGoodsOperationDTO.getIsMeal());

        //赋值SKU
        List<Map<String, Object>> skus = proxyGoodsOperationDTO.getSkuList();

        List<GoodsSku> goodsSkus = new ArrayList<>();
        Double minPrice = null;
        Double minVipPrice = null;
        String greenScore = "0";
        for (Map<String, Object> map : skus) {
            if (map.containsKey("id")) {
                //校验商品是否存在
                GoodsSku goodsSku = goodsSkuService.getById(map.get("id").toString());
                if (goodsSku == null) {
                    throw new ServiceException(ResultCode.GOODS_NOT_EXIST);
                }

                Double cost = map.containsKey(GoodsSku.COST_KEY) ? Double.valueOf(map.get(GoodsSku.COST_KEY).toString()) : 0;
                //校验价格是否小于原价
                Double price = map.containsKey(GoodsSku.PRICE_KEY) ? Double.valueOf(map.get(GoodsSku.PRICE_KEY).toString()) : 0;
                Double vipPrice = map.containsKey(GoodsSku.VIP_PRICE_KEY) ? Double.valueOf(map.get(GoodsSku.VIP_PRICE_KEY).toString()) : 0;
                if (null == minPrice) {
                    minPrice = price;
                    if(map.containsKey(GoodsSku.GREEN_SCORE) && null!=map.get(GoodsSku.GREEN_SCORE)){
                        greenScore = String.valueOf(map.get(GoodsSku.GREEN_SCORE));
                    }
                } else {
                    if (price < minPrice) {
                        minPrice = price;
                        if(map.containsKey(GoodsSku.GREEN_SCORE) && null!=map.get(GoodsSku.GREEN_SCORE)){
                            greenScore = String.valueOf(map.get(GoodsSku.GREEN_SCORE));
                        }
                    }
                }
                if (null == minVipPrice || vipPrice < minVipPrice) {
                    minVipPrice = vipPrice;
                }
                if (price < cost) {
                    throw new ServiceException(ResultCode.PROXY_PRICE_CANT_SMALL_THAN_ORIGIN, goodsSku.getSimpleSpecs());
                }
                if (vipPrice > 0 && vipPrice < cost) {
                    throw new ServiceException("会员价不能小于原价");
                }
                goodsSku.setGoodsName(goods.getGoodsName());
                GoodsSkuBuilder.builderSingle(goodsSku, map);
                goodsSkus.add(goodsSku);
            }
        }
        if (null != greenScore) {
            try {
                goods.setDefaultSkuGreenScore(new BigDecimal(greenScore));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (null != minPrice) {
            goods.setPrice(minPrice); //最小价格
        }
        if (null != minVipPrice) {
            goods.setVipPrice(minVipPrice); //最小价格
        }

        if (goods.getIsVipGoods() == null || !goods.getIsVipGoods()) {
            goods.setVipPrice(null);
            for (GoodsSku goodsSku : goodsSkus) {
                goodsSku.setIsVipGoods(false);
                goodsSku.setVipPrice(null);
            }
        }

        if (goods.getIsVipGoods() != null && goods.getIsVipGoods() ) {
            if (goods.getVipPrice() == null || goods.getVipPrice() <= 0) {
                throw new ServiceException("会员商品，会员价不能为空或为0");
            }
        }
        if (CollectionUtil.isNotEmpty(proxyGoodsOperationDTO.getGoodsGalleryList())) {
            goods.setSmall(proxyGoodsOperationDTO.getGoodsGalleryList().get(0));
            goods.setBig(proxyGoodsOperationDTO.getGoodsGalleryList().get(0));
            goods.setOriginal(proxyGoodsOperationDTO.getGoodsGalleryList().get(0));
            goods.setThumbnail(proxyGoodsOperationDTO.getGoodsGalleryList().get(0));
        }
        goodsService.updateGoods(goods);
        goodsSkuService.updateBatch(goodsSkus);

        this.generateGoodsHandler(goods, proxyGoodsOperationDTO);
        this.sendGenerateGoods(Collections.singletonList(goods.getId()));
        //判断是否为分销商品,是则同步商品信息到分销商品列表
        log.info("同步分销商品, 是否分销商品字段值,同步代理分销商品 goods.getIsDistributionGoods():{}", goods.getIsDistributionGoods());
        if (null != goods.getIsDistributionGoods() && goods.getIsDistributionGoods()) {
            log.info("同步分销商品,开始同步");
            Objects.requireNonNull(threadConfig.getAsyncExecutor()).execute(() -> {
                List<GoodsSku> goodsSkuList = goodsSkuService.getGoodsSkuListByGoodsId(goods.getId());
                log.info("同步分销商品, goodsSkuList:{}", CollUtil.isNotEmpty(goodsSkuList) ? JSONArray.toJSONString(goodsSkuList) : "empty");
                if (goodsSkuList != null && !goodsSkuList.isEmpty()) {
                    String ids = goodsSkuList.stream().map(GoodsSku::getId).map(String::valueOf).collect(Collectors.joining(","));
                    distributionGoodsClient.distributionCheckGoodsAndStoreId(ids, goods.getStoreId());
                }
            });
        }
    }

    @Override
    public List<Goods> getProxyGoodsList(String supplierId,String supplierGoodsId) {
        LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CharSequenceUtil.isNotEmpty(supplierId), Goods::getSupplierId, supplierId);
        queryWrapper.eq(Goods::getSupplierGoodsId, supplierGoodsId);
        return this.goodsService.getBaseMapper().selectList(queryWrapper);
    }

    @Override
    public void generateFullEs(Integer isGreenGoods) {
        List<String> list = this.goodsService.getGoodsIdListByGreenFlag(isGreenGoods);
        if (null != list && !list.isEmpty()) {
            this.sendGenerateGoods(list);
        }
    }


    @Transactional
    @ShardingTransactionType(TransactionType.BASE)
    public void generatorGoods(List<String> goodsIds, String storeId) {
        List<GoodsSku> goodsSkus = new ArrayList<>();
        if (CollUtil.isNotEmpty(goodsIds)) {
            goodsSkus = this.goodsSkuService.getGoodsSkuListByGoodsId(goodsIds);
            // 发送生成商品信息
            this.sendGenerateGoods(goodsIds);
        } else if (CharSequenceUtil.isNotEmpty(storeId)) {
            goodsSkus = this.goodsSkuService.getGoodsSkuByList(GoodsSearchParams.builder().storeId(storeId).build());
            // 发送生成店铺商品信息
            applicationEventPublisher.publishEvent(TransactionCommitSendMQEvent.builder()
                    .source("生成店铺商品")
                    .exchange(amqpExchangeProperties.getGoods())
                    .routingKey(GoodsRoutingKey.GENERATOR_STORE_GOODS_INDEX)
                    .message(storeId).build());
        }
        for (GoodsSku sku : goodsSkus) {
            // 缓存替换为新的sku信息
            if (sku.getAuthFlag().equals(GoodsAuthEnum.PASS.name()) && GoodsMarketEnum.UPPER.name().equals(sku.getMarketEnable())) {
                cache.remove(GoodsSkuService.getCacheKeys(sku.getId()));
                cache.put(GoodsSkuService.getCacheKeys(sku.getId()), sku);
            }else{
                //否则，清除缓存中的sku数据
                cache.remove(GoodsSkuService.getCacheKeys(sku.getId()));
            }
        }
    }


    @Transactional
    @ShardingTransactionType(TransactionType.BASE)
    public void cleanGoods(List<String> goodsIds) {
        if (CollUtil.isNotEmpty(goodsIds)) {
            List<String> goodsCacheKeys = new ArrayList<>();
            List<String> goodsSkuCacheKeys = new ArrayList<>();
            // 遍历商品缓存key
            goodsIds.forEach(i -> goodsCacheKeys.add(CachePrefix.GOODS.getPrefix() + i));
            // 遍历商品sku缓存key
            this.goodsSkuService.getGoodsSkuIdListByGoodsId(GoodsSearchParams.builder().goodsIds(goodsIds).build()).forEach(i -> goodsSkuCacheKeys.add(GoodsSkuService.getCacheKeys(i)));
            // 发送删除商品信息
            this.sendDeleteGoods(goodsIds);
            // 清除缓存
            cache.multiDel(goodsCacheKeys);
            cache.multiDel(goodsSkuCacheKeys);
        }
    }


    /**
     * 发送生成ES商品索引
     *
     * @param goodIds 商品id集合
     */
    public void sendGenerateGoods(List<String> goodIds) {
        applicationEventPublisher.publishEvent(TransactionCommitSendMQEvent.builder().source("生成商品").exchange(amqpExchangeProperties.getGoods()).routingKey(GoodsRoutingKey.GENERATOR_GOODS_INDEX).message(goodIds).build());
    }

    public void sendDeleteGoods(List<String> goodIds) {

        applicationEventPublisher.publishEvent(TransactionCommitSendMQEvent.builder().source("删除商品").exchange(amqpExchangeProperties.getGoods()).routingKey(GOODS_DELETE).message(goodIds).build());

    }

    public void sendGrabGoods(Goods goods) {
        applicationEventPublisher.publishEvent(
                TransactionCommitSendMQEvent.builder()
                        .source("商品采集完成").exchange(amqpExchangeProperties.getGoods())
                        .routingKey(GoodsRoutingKey.GOODS_GRAB_COMPLETE).message(goods).build());

    }

    @Override
    @Transactional
    @ShardingTransactionType(TransactionType.BASE)
    public boolean updateResultGoods(List<String> goodsIds, Boolean isResultGoods) {
        // 更新商品信息
        LambdaUpdateWrapper<Goods> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(Goods::getId,goodsIds);
        updateWrapper.set(Goods::getIsResultGoods,isResultGoods);
        boolean result = goodsService.update(updateWrapper);

        //更新SKU信息
        LambdaUpdateWrapper<GoodsSku> skuLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        skuLambdaUpdateWrapper.in(GoodsSku::getGoodsId,goodsIds);
        skuLambdaUpdateWrapper.set(GoodsSku::getIsResultGoods,isResultGoods);
        goodsSkuService.update(skuLambdaUpdateWrapper);

        // 发送生成商品索引信息
        this.sendGenerateGoods(goodsIds);
        return result;
    }

    /**
     * 发送删除商品sku的信息
     *
     * @param goodsIds 商品id
     */
    @Transactional
    @ShardingTransactionType(TransactionType.BASE)
    public void sendDeleteGoodsSku(List<String> goodsIds) {
        applicationEventPublisher.publishEvent(TransactionCommitSendMQEvent.builder().source("删除商品").exchange(amqpExchangeProperties.getGoods()).routingKey(GoodsRoutingKey.SKU_DELETE).message(goodsIds).build());
    }


    /**
     * 添加商品默认图片
     *
     * @param origin 图片
     * @param goods  基础商品
     */
    private void setGoodsGalleryParam(String origin, Goods goods) {
        //供应商商品，图片切割规律不明，暂不处理
        goods.setOriginal(origin);
        goods.setSmall(origin);
        goods.setThumbnail(origin);
    }


    /**
     * 根据商品分组商品sku及其规格信息
     *
     * @param goodsSkuVOList 商品VO列表
     * @return 分组后的商品sku及其规格信息
     */
    private List<GoodsSkuSpecVO> groupBySkuAndSpec(List<GoodsSkuVO> goodsSkuVOList) {

        List<GoodsSkuSpecVO> skuSpecVOList = new ArrayList<>();
        for (GoodsSkuVO goodsSkuVO : goodsSkuVOList) {
            GoodsSkuSpecVO specVO = new GoodsSkuSpecVO();
            specVO.setSkuId(goodsSkuVO.getId());
            specVO.setSpecValues(goodsSkuVO.getSpecList());
            specVO.setQuantity(goodsSkuVO.getQuantity());
            skuSpecVOList.add(specVO);
        }
        return skuSpecVOList;
    }

    private Goods wrapperGoods(GoodsOperationDTO goodsOperationDTO) {
        // 是否存在规格
        if (goodsOperationDTO.getSkuList() == null || goodsOperationDTO.getSkuList().isEmpty()) {
            throw new ServiceException(ResultCode.MUST_HAVE_GOODS_SKU);
        }
        //判断当前账号的店铺是否是免税店铺,是则更标识为免税商品
        AuthUser authUser = UserContext.getCurrentUser();
        if (SceneEnums.STORE.equals(authUser.getScene())) {
            String storeId = authUser.getExtendId();
            if (StrUtil.isNotEmpty(storeId)) {
                StoreVO store = storeClient.getStore(storeId);
                if (null != store && null != store.getIsFree() && store.getIsFree()) {
                    goodsOperationDTO.setIsFree(true);
                    goodsOperationDTO.setThirdPartyPlatformType(4);
                }

            }
        }

        if (goodsOperationDTO.getIsFree() != null && goodsOperationDTO.getIsFree()) {
            if (StrUtil.isEmpty(goodsOperationDTO.getBrandId())) {
                throw new ServiceException("免税商品必选品牌");
            }
            if (StrUtil.isEmpty(goodsOperationDTO.getStoreCategoryPath())) {
                throw new ServiceException("免税商品必选店铺分类");
            }
        }

        //商品展示价格为SKU的最低价格
        Double minPrice = null;
        Double minVipPrice = null;
        String skuGreenScore = null;
        BigDecimal defaultSkuGreenScore = BigDecimal.ZERO;
        boolean isFree = false;
        String thirdPartyPlatformId = null;
        for (Map<String, Object> map : goodsOperationDTO.getSkuList()) {
            if (map.containsKey("") || map.containsValue("")) {
                throw new ServiceException(ResultCode.GOODS_SKU_SPEC_VALUE_CANT_EMPTY);
            }
            if (map.get(GoodsSku.PRICE_KEY) != null) {
                Object priceStr = map.get(GoodsSku.PRICE_KEY);
                String price = ObjectUtil.toString(priceStr);
                Object skuGreenScoreStr = map.get(GoodsSku.GREEN_SCORE);

                if (minPrice == null) {
                    minPrice = Double.parseDouble(price);
                    skuGreenScore = ObjectUtil.toString(skuGreenScoreStr);
//                    if (map.get("thirdPartyPlatformId") != null) {
//                        thirdPartyPlatformId = ObjectUtil.toString(map.get("thirdPartyPlatformId"));
//                    }
                } else if (minPrice > Double.parseDouble(price)) {
                    minPrice = Double.parseDouble(price);
                    skuGreenScore = ObjectUtil.toString(skuGreenScoreStr);
//                    if (map.get("thirdPartyPlatformId") != null) {
//                        thirdPartyPlatformId = ObjectUtil.toString(map.get("thirdPartyPlatformId"));
//                    }
                }

            }
            if (map.get(GoodsSku.VIP_PRICE_KEY) != null) {
                Object priceStr = map.get(GoodsSku.VIP_PRICE_KEY);
                String price = ObjectUtil.toString(priceStr);
                if (minVipPrice == null) {
                    minVipPrice = Double.parseDouble(price);
                } else if (minVipPrice > Double.parseDouble(price)) {
                    minVipPrice = Double.parseDouble(price);
                }
            }
            if (map.get("isFree") != null) {
                Object isFreeStr = map.get(GoodsSku.IS_FREE_KEY);
                log.info("ObjectUtil.toString(isFreeStr) == {}",  ObjectUtil.toString(isFreeStr));
                if (Boolean.TRUE.equals(isFreeStr) || String.valueOf(1).equals(ObjectUtil.toString(isFreeStr))) {
                    isFree = true;
                }
            }
        }
        goodsOperationDTO.setPrice(minPrice);
        goodsOperationDTO.setVipPrice(minVipPrice);
        log.info("1isFree 1 = {}", isFree);
        goodsOperationDTO.setIsFree(isFree);
//        goodsOperationDTO.setThirdPartyPlatformId(thirdPartyPlatformId);
        if (isFree) {
            goodsOperationDTO.setThirdPartyPlatformType(4);
        }
        if (null != skuGreenScore) {
            try {
                defaultSkuGreenScore = new BigDecimal(skuGreenScore);
                goodsOperationDTO.setDefaultSkuGreenScore(defaultSkuGreenScore);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        Goods goods = new Goods(goodsOperationDTO);

        // 检查商品信息
        this.checkBase(goods, goodsOperationDTO.getTemplateGoodsFlag());
        // 添加相册
        if (goodsOperationDTO.getGoodsGalleryList() != null && !goodsOperationDTO.getGoodsGalleryList().isEmpty()) {
            //向goods加入图片
            this.setGoodsGalleryParam(goodsOperationDTO.getGoodsGalleryList().get(0), goods);
        }
        // 添加商品参数
        if (goodsOperationDTO.getGoodsParamsDTOList() != null && !goodsOperationDTO.getGoodsParamsDTOList().isEmpty()) {
            goods.setParams(JSONUtil.toJsonStr(goodsOperationDTO.getGoodsParamsDTOList()));
        }

        SceneHelp.objectHandler(goods);

        GoodsSearchParams build = GoodsSearchParams.builder().eqGoodsName(goods.getGoodsName()).storeId(goods.getStoreId()).build();
        if (CharSequenceUtil.isNotEmpty(goods.getId())) {
            build.setNeId(goods.getId());
        }
        return goods;
    }

    /**
     * 封装供应商商品
     *
     * @param supplierGoodsOperationDTO 供应商商品操作DTO
     * @return 供应商商品
     */
    private Goods wrapperGoods(SupplierGoodsOperationDTO supplierGoodsOperationDTO) {
        Goods goods = wrapperGoods((GoodsOperationDTO) supplierGoodsOperationDTO);
        goods.setSupportPurchase(supplierGoodsOperationDTO.getSupportPurchase());
        goods.setSupportProxy(supplierGoodsOperationDTO.getSupportProxy());
        if (Boolean.TRUE.equals(supplierGoodsOperationDTO.getSupportPurchase())) {
            goods.setPurchaseRule(supplierGoodsOperationDTO.getPurchaseRule().name());
        }

        if (goods.getPrice() == null && (supplierGoodsOperationDTO.getWholesaleList() != null && !supplierGoodsOperationDTO.getWholesaleList().isEmpty())) {
            goods.setPrice(supplierGoodsOperationDTO.getWholesaleList().get(0).getPrice());
        }
        if (goods.getPrice() == null && (supplierGoodsOperationDTO.getWholesaleList() != null && !supplierGoodsOperationDTO.getWholesaleList().isEmpty())) {
            goods.setVipPrice(supplierGoodsOperationDTO.getWholesaleList().get(0).getPrice());
        }
        return goods;
    }

    /**
     * 基础商品信息检测
     *
     * @param goods 商品
     */
    private void checkBase(Goods goods, boolean templateGoodsFlag) {
        StoreVO store = storeClient.getStore(UserContext.getCurrentUser().getExtendId());
        if (store.getSelfOperated() != null) {
            goods.setSelfOperated(store.getSelfOperated());
        }
        goods.setStoreId(store.getId());
        goods.setStoreName(store.getStoreName());
        goods.setSelfOperated(store.getSelfOperated());
        //物流模板设置空，则免运费
        if (CharSequenceUtil.isEmpty(goods.getTemplateId())) {
            goods.setTemplateId("0");
        }
        //检查商品是否存在--修改商品时使用
        if (goods.getId() != null && !templateGoodsFlag) {
            this.checkExist(goods.getId());
        } else {
            //评论次数
            goods.setCommentNum(0);
            //购买次数
            goods.setBuyCount(0);
            //购买次数
            goods.setQuantity(0);
            //商品评分
            goods.setGrade(100.0);
        }

        //获取商品系统配置决定是否审核
        Setting setting = settingClient.get(SettingEnum.GOODS_SETTING.name());
        GoodsSetting goodsSetting = JSONUtil.toBean(setting.getSettingValue(), GoodsSetting.class);
        //是否需要审核
        goods.setAuthFlag(Boolean.TRUE.equals(goodsSetting.getGoodsCheck()) ? GoodsAuthEnum.TOBEAUDITED.name() : GoodsAuthEnum.PASS.name());
    }


    /**
     * 生成商品处理业务，比如sku构造，相册构造等
     *
     * @param goods             商品信息
     * @param goodsOperationDTO 供应商商品信息
     */
    @Transactional
    public String generateGoodsHandler(Goods goods, GoodsOperationDTO goodsOperationDTO) {
        // 判定是否是供应商商品操作
        boolean isSupplierOperation = goodsOperationDTO instanceof SupplierGoodsOperationDTO;

        //供应商商品操作，赋值
        SupplierGoodsOperationDTO supplierGoodsOperationDTO = isSupplierOperation ? (SupplierGoodsOperationDTO) goodsOperationDTO :
                new SupplierGoodsOperationDTO();

        List<String> keepIdList = new ArrayList<>();
        //sku 信息
        List<GoodsSku> skuList;
        // 是否重新生成sku
        if (Boolean.TRUE.equals(goodsOperationDTO.getRegeneratorSkuFlag())) {
            // 重新生成sku，删除原sku信息
            skuList = GoodsSkuBuilder.buildBatch(goods, goodsOperationDTO.getSkuList());
            this.renderGoodsSkuList(skuList);
            skuList.forEach(item -> keepIdList.add(item.getId()));

            List<GoodsSkuVO> goodsListByGoodsId =
                    this.goodsSkuService.getGoodsListByGoodsId(GoodsSearchParams.builder().goodsId(goods.getId()).build());
            List<String> oldSkuIds = new ArrayList<>();
            // 旧sku id集合
            for (GoodsSkuVO goodsSkuVO : goodsListByGoodsId) {
                if (!keepIdList.contains(goodsSkuVO.getId())) {
                    oldSkuIds.add(goodsSkuVO.getId());
                }
            }
            //发送mq消息，删除会员收藏的商品
            this.sendDeleteGoodsSku(oldSkuIds);

            //删除原有sku数据
            if (oldSkuIds.size() > 0) {
                this.goodsSkuService.delete(oldSkuIds);
            }
        } else {
            skuList = new ArrayList<>();
            for (Map<String, Object> map : goodsOperationDTO.getSkuList()) {
                GoodsSku sku = GoodsSkuBuilder.build(goods, map);
                this.renderGoodsSku(sku);
                skuList.add(sku);
            }
        }
        //不是会员清空会员价格
        if (goods.getIsVipGoods()!=null && !goods.getIsVipGoods()) {
            for (GoodsSku goodsSku : skuList) {
                goodsSku.setIsVipGoods(false);
                goodsSku.setVipPrice(null);
            }
        }
        //是会员价格不能为空
        if (goods.getIsVipGoods()!=null && goods.getIsVipGoods()) {
            for (GoodsSku goodsSku : skuList) {
                if (goodsSku.getVipPrice() == null || goodsSku.getVipPrice()==0D) {
                    throw new ServiceException("会员价不能为空或为0");
                }
            }
        }

        //赋值sku里的绿色积分分佣值 greenScoreView
        initSetting();
        if(CollUtil.isNotEmpty(skuList)){
            skuList.stream().forEach(sku->{
                //开启一级分销,则直接赋值绿色积分的值赋值需要展示的绿色积分佣金值
                if (sku.getIsLevelDistribution() != null && sku.getIsLevelDistribution()) {
                    sku.setGreenScoreView(sku.getGreenScore());
                }else{
                    //计算绿色积分的分佣值
                    sku.setGreenScoreView(calcGreenOmitGreenScore(sku));
                }
                log.info("赋值sku里的绿色积分分佣值 , sku.id:{}, 赋值后:{}", sku.getId(), sku.getGreenScoreView() != null ? sku.getGreenScoreView() : null);
            });
        }

        //如果是供应商商品操作，设置批发信息
        if (isSupplierOperation)
            this.renderGoodsSkuWholesale(skuList, supplierGoodsOperationDTO, goods.getId());

        //修改商品sku信息
        this.goodsSkuService.saveOrUpdateBatch(skuList);
        if (goods.getIsVipGoods()!=null && !goods.getIsVipGoods()) {
            for (GoodsSku goodsSku : skuList) {
                LambdaUpdateWrapper<GoodsSku> goodsSkuLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                goodsSkuLambdaUpdateWrapper.set(GoodsSku::getVipPrice, null);
                goodsSkuLambdaUpdateWrapper.eq(GoodsSku::getId, goodsSku.getId());
                this.goodsSkuService.update(goodsSkuLambdaUpdateWrapper);
            }
        }
        // 更新商品sku库存信息
        this.goodsSkuService.updateStock(skuList);

        //更新商品库存信息
        this.goodsService.updateStock(skuList);

        //删除sku相册
        this.goodsGalleryService.removeByGoodsId(goods.getId());

        // 添加商品图片
        this.goodsGalleryService.add(goodsOperationDTO.getGoodsGalleryList(), goods.getId());

        List<String> goodsIds = Lists.newArrayList();
        goodsIds.add(goods.getId());
//        LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(Goods::getSupplierGoodsId, goods.getId());
//        List<Goods> goodsList = goodsService.list(queryWrapper);
//        if (!goodsList.isEmpty()) {
//            goodsList.stream().forEach(goods1 -> {
//                //删除店铺原有sku， 把供应商的sku同步过去
//                List<GoodsSku> goodsSkuList = goodsSkuService.list(new LambdaQueryWrapper<GoodsSku>().eq(GoodsSku::getGoodsId, goods.getId()));
//                List<GoodsSku> goodsSkus = this.storeOwnHandler(goodsSkuList, goods1);
//                LambdaUpdateWrapper<GoodsSku> goodsSkuLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
//                goodsSkuLambdaUpdateWrapper.eq(GoodsSku::getGoodsId, goods1.getId());
//                goodsSkuLambdaUpdateWrapper.set(GoodsSku::getDeleteFlag, true);
//                goodsSkuService.update(goodsSkuLambdaUpdateWrapper);
//
//                goodsSkuService.saveBatch(goodsSkus);
//                //删除sku相册
//                this.goodsGalleryService.removeByGoodsId(goods1.getId());
//                // 添加商品图片
//                this.goodsGalleryService.add(goodsOperationDTO.getGoodsGalleryList(), goods1.getId());
//            });
//        }

        //如果商品状态值不对，则es索引移除
        if (goods.getAuthFlag().equals(GoodsAuthEnum.PASS.name()) && goods.getMarketEnable().equals(GoodsMarketEnum.UPPER.name())) {
            this.goodsService.clearCache(goods.getId());
            skuList.forEach(i -> this.goodsSkuService.clearCache(i.getId()));
        }


        //如果是供应商商品操作，设置批发信息
        if (isSupplierOperation && (supplierGoodsOperationDTO.getWholesaleList() != null)) {
            wholesaleService.saveWholesale(goods.getId(), supplierGoodsOperationDTO.getWholesaleList());
        }
        //用stream判断价格不为空的取skuList最低价的id
//        List<String> skuIdList = skuList.stream().filter(e -> e.getPrice() != null).map(e -> e.getId()).collect(Collectors.toList());
//        return CollUtil.isNotEmpty(skuIdList) ? String.join(",", skuIdList.toArray(new String[0])) : null;
        return goods.getId();
    }

    private Double calcGreenOmitGreenScore(GoodsSku goodsSku) {
        Double result = 0.0, number = 0.0;
        if (Boolean.TRUE.equals(goodsSku.getIsGreenGoods())) {
            //比例
            number = CurrencyUtil.div(settings.get(SettingEnum.GREEN_GOODS).getDouble("lowerProportion"), 100);
        } else {
            //比例
            number = CurrencyUtil.div(settings.get(SettingEnum.NOT_GREEN_GOODS).getDouble("lowerProportion"), 100);
        }
        //优惠金额
        result = CurrencyUtil.mul(goodsSku.getGreenScore(), number);
        return result;
    }

    /**
     * 生成商品处理业务，比如sku构造，相册构造等
     *
     * @param goods             商品信息
     * @param proxyGoodsOperationDTO 供应商商品信息
     */
    @Transactional
    public void generateGoodsHandler(Goods goods, ProxyGoodsOperationDTO proxyGoodsOperationDTO) {
        //sku 信息
        List<GoodsSku>   skuList = new ArrayList<>();
            for (Map<String, Object> map : proxyGoodsOperationDTO.getSkuList()) {
                GoodsSku sku = GoodsSkuBuilder.build(goods, map);
                this.renderGoodsSku(sku);
                skuList.add(sku);
            }
        //不是会员清空会员价格
        if (goods.getIsVipGoods()!=null && !goods.getIsVipGoods()) {
            for (GoodsSku goodsSku : skuList) {
                goodsSku.setIsVipGoods(false);
                goodsSku.setVipPrice(null);
            }
        }
        //是会员价格不能为空
        if (goods.getIsVipGoods()!=null && goods.getIsVipGoods()) {
            for (GoodsSku goodsSku : skuList) {
                if (goodsSku.getVipPrice() == null || goodsSku.getVipPrice()==0D) {
                    throw new ServiceException("会员价不能为空或为0");
                }
            }
        }

        //修改商品sku信息
        this.goodsSkuService.saveOrUpdateBatch(skuList);
        if (goods.getIsVipGoods()!=null && !goods.getIsVipGoods()) {
            for (GoodsSku goodsSku : skuList) {
                LambdaUpdateWrapper<GoodsSku> goodsSkuLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                goodsSkuLambdaUpdateWrapper.set(GoodsSku::getVipPrice, null);
                goodsSkuLambdaUpdateWrapper.eq(GoodsSku::getId, goodsSku.getId());
                this.goodsSkuService.update(goodsSkuLambdaUpdateWrapper);
            }
        }
        // 更新商品sku库存信息
        this.goodsSkuService.updateStock(skuList);

        //更新商品库存信息
        this.goodsService.updateStock(skuList);

        //删除sku相册
        this.goodsGalleryService.removeByGoodsId(goods.getId());

        // 添加商品图片
        this.goodsGalleryService.add(proxyGoodsOperationDTO.getGoodsGalleryList(), goods.getId());

        List<String> goodsIds = Lists.newArrayList();
        goodsIds.add(goods.getId());
//        LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(Goods::getSupplierGoodsId, goods.getId());
//        List<Goods> goodsList = goodsService.list(queryWrapper);
//        if (!goodsList.isEmpty()) {
//            goodsList.stream().forEach(goods1 -> {
//                //删除店铺原有sku， 把供应商的sku同步过去
//                List<GoodsSku> goodsSkuList = goodsSkuService.list(new LambdaQueryWrapper<GoodsSku>().eq(GoodsSku::getGoodsId, goods.getId()));
//                List<GoodsSku> goodsSkus = this.storeOwnHandler(goodsSkuList, goods1);
//                LambdaUpdateWrapper<GoodsSku> goodsSkuLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
//                goodsSkuLambdaUpdateWrapper.eq(GoodsSku::getGoodsId, goods1.getId());
//                goodsSkuLambdaUpdateWrapper.set(GoodsSku::getDeleteFlag, true);
//                goodsSkuService.update(goodsSkuLambdaUpdateWrapper);
//
//                goodsSkuService.saveBatch(goodsSkus);
//                //删除sku相册
//                this.goodsGalleryService.removeByGoodsId(goods1.getId());
//                // 添加商品图片
//                this.goodsGalleryService.add(goodsOperationDTO.getGoodsGalleryList(), goods1.getId());
//            });
//        }

        //如果商品状态值不对，则es索引移除
        if (goods.getAuthFlag().equals(GoodsAuthEnum.PASS.name()) && goods.getMarketEnable().equals(GoodsMarketEnum.UPPER.name())) {
            this.goodsService.clearCache(goods.getId());
            skuList.forEach(i -> this.goodsSkuService.clearCache(i.getId()));
        }

    }


    /**
     * 格式化SKU为供应商所有
     *
     * @param goodsSkus        商品sku
     * @param goodsServiceById
     */
    private List<GoodsSku> storeOwnHandler(List<GoodsSku> goodsSkus, Goods goodsServiceById) {
        //接收sku集合
        List<GoodsSku> result = new ArrayList<>();
        Double minPrice = null;
        //格式化商品为店铺所有，需要将商品id置空，以及配置店铺id和店铺名称
        for (GoodsSku goodsSku : goodsSkus) {
            try {
                GoodsSku sku = goodsSku.clone();

                String supplierGoodsId = goodsSku.getGoodsId();
                String supplierSkuId = goodsSku.getId();
                String supplierId = goodsSku.getStoreId();
                String supplierName = goodsSku.getStoreName();

                sku.setId(null);
                sku.setGoodsId(goodsServiceById.getId());
                sku.setStoreId(goodsServiceById.getStoreId());
                sku.setStoreName(goodsServiceById.getStoreName());
                sku.setMarketEnable(GoodsMarketEnum.DOWN.name());

                sku.setSupplierGoodsId(supplierGoodsId);
                sku.setSupplierSkuId(supplierSkuId);
                sku.setSupplierId(supplierId);
                sku.setSupplierName(supplierName);

                sku.setSupportProxy(false);
                sku.setSupportPurchase(false);
                sku.setSalesModel(SalesModeEnum.RETAIL.name());
                sku.setIsProxyGoods(true);
                sku.setFreightTemplateId(goodsServiceById.getTemplateId());

                //将代理商的价格设置为当前商品的成本价
                sku.setCost(goodsSku.getPrice());
                //默认代理商的价格为当前商品的价格的1.15倍
                BigDecimal price = BigDecimal.valueOf(goodsSku.getRetailPrice() != null ? goodsSku.getRetailPrice() : Double.MAX_VALUE);
                if (goodsSku.getRetailPrice() == null || goodsSku.getRetailPrice().equals(0D)) {
                    price = BigDecimal.valueOf(goodsSku.getPrice()).multiply(BigDecimal.valueOf(1.15)).setScale(2, RoundingMode.HALF_UP);
                }
                sku.setPrice(price.doubleValue());

                if (minPrice == null || sku.getPrice() < minPrice) {
                    minPrice = sku.getPrice();
                }
                result.add(sku);
            } catch (CloneNotSupportedException e) {
                throw new RuntimeException(e);
            }
        }
        goodsServiceById.setPrice(minPrice);
        result.forEach(SceneHelp::objectHandler);
        return result;
    }

    /**
     * 批量渲染商品sku
     *
     * @param goodsSkuList sku集合
     */
    void renderGoodsSkuList(List<GoodsSku> goodsSkuList) {
        for (GoodsSku goodsSku : goodsSkuList) {
            extendOldSkuValue(goodsSku);
            this.renderImages(goodsSku);
        }
    }

    /**
     * 渲染sku批发规则
     *
     * @param goodsSkus         sku集合
     * @param goodsOperationDTO 商品操作DTO
     * @param goodsId           商品id
     */
    @Transactional
    public void renderGoodsSkuWholesale(List<GoodsSku> goodsSkus, SupplierGoodsOperationDTO goodsOperationDTO, String goodsId) {
        if (goodsOperationDTO.getSalesModel().equals(SalesModeEnum.WHOLESALE.name())
                || goodsOperationDTO.getSalesModel().equals(SalesModeEnum.PURCHASING.name())) {
            if (CollUtil.isEmpty(goodsOperationDTO.getWholesaleList())) {
                throw new ServiceException(ResultCode.MUST_HAVE_SALES_MODEL);
            }
            List<WholesaleDTO> collect =
                    goodsOperationDTO.getWholesaleList().stream().sorted(Comparator.comparing(WholesaleDTO::getPrice)).toList();
            this.checkWholesaleList(goodsSkus, collect);
            for (GoodsSku skus : goodsSkus) {
                skus.setPrice(collect.get(0).getPrice());
                skus.setCost(collect.get(0).getPrice());
            }
            wholesaleService.removeByGoodsId(goodsId);
            wholesaleService.saveWholesale(goodsId, collect);
        }
    }

    /**
     * 校验批发规则
     *
     * @param wholesaleList 批发规则
     */
    private void checkWholesaleList(List<GoodsSku> goodsSkus, List<WholesaleDTO> wholesaleList) {
        for (WholesaleDTO wholesaleDTO : wholesaleList) {
            if (wholesaleDTO.getPrice() == null || wholesaleDTO.getPrice() <= 0 || wholesaleDTO.getNum() == null || wholesaleDTO.getNum() <= 0) {
                throw new ServiceException(ResultCode.HAVE_INVALID_SALES_MODEL);
            }
        }
        for (GoodsSku sku : goodsSkus) {
            if (sku.getQuantity() < wholesaleList.get(0).getNum()) {
                throw new ServiceException(ResultCode.GOODS_SKU_QUANTITY_MUST_GREAT_THAN_WHOLESALE_RULE);
            }
        }
    }

    /**
     * 渲染商品sku
     *
     * @param goodsSku sku
     */
    void renderGoodsSku(GoodsSku goodsSku) {
        extendOldSkuValue(goodsSku);
        this.renderImages(goodsSku);
    }

    /**
     * 将原sku的一些不会直接传递的值放到新的sku中
     *
     * @param goodsSku 商品sku
     */
    private void extendOldSkuValue(GoodsSku goodsSku) {
        if (CharSequenceUtil.isNotEmpty(goodsSku.getGoodsId())) {
            GoodsSku oldSku = this.goodsSkuService.getById(goodsSku.getId());
            if (oldSku != null) {
                goodsSku.setCommentNum(oldSku.getCommentNum());
                goodsSku.setViewCount(oldSku.getViewCount());
                goodsSku.setBuyCount(oldSku.getBuyCount());
                goodsSku.setGrade(oldSku.getGrade());
            }
        }
    }

    /**
     * 渲染sku图片
     *
     * @param goodsSku sku
     */
    private void renderImages(GoodsSku goodsSku) {
        JSONObject jsonObject = JSONUtil.parseObj(goodsSku.getSpecs());
        List<Map<String, String>> images = jsonObject.get("images", List.class);
        if (images != null && !images.isEmpty()) {
            GoodsGallery goodsGallery = goodsGalleryService.getGoodsGallery(images.get(0).get("url"));
            goodsSku.setBig(goodsGallery.getOriginal());
            goodsSku.setOriginal(goodsGallery.getOriginal());
            goodsSku.setThumbnail(goodsGallery.getThumbnail());
            goodsSku.setSmall(goodsGallery.getSmall());
        }
    }

    /**
     * 判断商品是否存在
     *
     * @param goodsId 商品id
     * @return 商品信息
     */
    private Goods checkExist(String goodsId) {
        Goods goods = this.goodsService.getById(goodsId);
        if (goods == null) {
            log.error("商品ID为" + goodsId + "的商品不存在");
            return null;
        }
        return goods;
    }

    /**
     * 发送更新装修商品数据
     *
     * @param goodIds 商品id集合
     */
    public void sendUpdatePageDataGoods(List<String> goodIds) {
        applicationEventPublisher.publishEvent(TransactionCommitSendMQEvent.builder().source("更新装修商品数据").exchange(amqpExchangeProperties.getGoods()).routingKey(GoodsRoutingKey.UPDATE_PAGE_DATA_GOODS).message(goodIds).build());
    }

    @Override
    public ResultMessage<Object> updateIndexByStoreId(String storeId) {
        LambdaQueryWrapper<Goods> goodsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        goodsLambdaQueryWrapper.eq(Goods::getStoreId, storeId);
        goodsLambdaQueryWrapper.eq(Goods::getMarketEnable, GoodsMarketEnum.UPPER.name());
        goodsLambdaQueryWrapper.eq(Goods::getAuthFlag, GoodsAuthEnum.PASS.name());
        goodsLambdaQueryWrapper.eq(Goods::getDeleteFlag, Boolean.FALSE);
        goodsLambdaQueryWrapper.select(Goods::getId, Goods::getStoreId);
        List<Goods> goodsList = goodsService.list(goodsLambdaQueryWrapper);
        List<String> goodsIdList = goodsList.stream().map(Goods::getId).map(String::valueOf).collect(Collectors.toList());
        this.sendGenerateGoods(goodsIdList);
        return ResultUtil.success();
    }

    private void initSetting(){
        SettingClient settingClient = SpringContextUtil.getBean(SettingClient.class);

        com.alibaba.fastjson.JSONObject greenGoodsSetting = com.alibaba.fastjson.JSONObject.parseObject(settingClient.get(SettingEnum.GREEN_GOODS.name()).getSettingValue());
        com.alibaba.fastjson.JSONObject goodsSetting = com.alibaba.fastjson.JSONObject.parseObject(settingClient.get(SettingEnum.NOT_GREEN_GOODS.name()).getSettingValue());

        settings.put(SettingEnum.GREEN_GOODS, greenGoodsSetting);
        settings.put(SettingEnum.NOT_GREEN_GOODS, goodsSetting);
    }
}
